Introduction
One of the key things to understand when you handle data in C is Arrays. When you want to collect your data values into a compact container of variables, which are indexed and organised; arrays are what you will need. Arrays enable you to structure a list of values that are stored, and allowing access by simple indexing with assigning a value to the data element you have selected.
Assigning and Using Arrays
With arrays, you can store as many items in the container structure (not be be confused with struct), with each stored value has an index assigned; so your first entry is zero in the index and the next item will be one, and so on as the index increments by one. Once a data item has been assigned and entered in the array, you cannot remove or move the element; All other data items will retain their index positions with the entry you might want to remove. As long as you initialise the array by defining the size, you can enter as many data element items you have permitted within the size set. So if you enter 10 as the size of the array, you cannot go over. If you do, your program will simply crash. You also cannot add extra elements on top of the maximum size you have defined; once you have created it, you have to stick to the set parameters within it's size. That is why a C Array in it's basic sense is defined in Computer Science as a Fixed Sized Array, or a Static Array.
When you assign an array with data, you can only use the same data type you have used when initialising. You cannot mix the data types within that same array. So if you initialise the array with an integer, that is what you have to use when you assign values to the data element items within the array.
Now we have gone through the basic theory of what an Array is, we will start by going into the practical part, which involves programming and understanding how it works in a real time coding environment.
datatype identifier_array[N];
The example above shows the basic set up of an array. The first section is the datatype, which is where you declare the data type you want to use for your array. Then identifier_array is simply the identifier name for the array variable and the square brackets [] (also known as an Array Subscript) which is where you would assign the size of the array. The N inside the square brackets is the number that you will use to set the how many elements can be inside the array. This can only be an integer, so you cannot set the size with floats or any other type of data. With setting the size, the last element index will be one less than the set max size; so for example if you set the array as int item[6];, the last element will be assigned as item[5]. So the first element will also have a index of item[0], and so on (as mentioned earlier).
The snippet below shows a description of how a array is initialised. There are a few ways to set up a array. You can do it by initialising the array by assigning the values inside curly brackets like the example below.
float m[5] = { 1.5f, 2.0f, 0.2f, 7.0f 3.2f };
Or you can just simply declare an array which contains 5 elements, like the example below.
int k[5]; // initialise the size of the array to
// five elements
......
// Now assign values to each element by identifying
// each one by their index number
k[0] = 14;
k[1] = 43;
k[2] = 500;
k[3] = 88;
k[4] = 235;
When you use an array, you can get access of an element by using the square brackets to select it using by the index number. Whilst using C arrays, there are no barriers to prevent you going over the pitfalls; as there is no bounds checking. This means that if you set the size of an array int r[5] and you assigned a value on element r[5]=10;, you program will run into unintentional consequences; as you have gone over bounds, and possibly causing over data values to be corrupted, making the program unstable; and with some compiler crashing abruptly. As long as you have set to the array size and keep within it, you can assign values to the array elements with no problem.
Multi-Dimensional Arrays
As you have seen with the article so far, creating a basic array is straight-forward as it is using a one-dimensional Array. it is also possible to use multi-dimensional arrays. As shown being declared in the snippet below.
int table[3][4];
The declaration of the multi-dimensional array above, shows that it is two-dimensional as it has two square brackets. The table variable array shows within the two square brackets, will have 3 rows and 4 columns. The best practice to use multi-dimensional arrays is to process it through nested loops(which will be shown in the main program code); it is also common to assign the data in this way, and gain access to the element data, just like the one-dimensional arrays done earlier. Similar to the one-dimensional loops, multi-dimensional loops can be initialised at declaration like these following examples.
// FIRST EXAMPLE
int table[3][4]{ 10,20,30,40 // first row
80,90,100,110, // second row
120,140,160,180 // third row
};
// SECOND EXAMPLE
int table[3][4]{ {10,20,30,40}, // first row
{80,90,100,110}, // second row
{80,90,100,110}, // second row
{120,140,160,180} }; // third row
The second example shows that the column data is grouped encapsulated in extra curly brackets within each row element (confusing at first, but you will get it in time..), this is an option as it keeps the code clean and easier to follow if you were to use large amounts of elements in a multi-dimensional array.
Example Code In Detail
With this covered, we will go through the article code. The first thing we do with this program is define a global macro defined as NUM_COL_ROWS; this we will use to set the size of the array. It will be a const value as it will not change during run time. It is useful this way as it is a value which you can change during coding, without changing all the values and conditions by hand as you will see later in the multi-dimensional segment. It is useful to do this in more sophisticated programs in C.
// MACRO PREPROCESSOR WHICH DEFINES THE NUMBER OF ELEMENTS
// INSIDE THE MULTI-DIMENSIONAL ARRAY
#define NUM_COL_ROWS 8
Once we enter the int main() function, we will initialise the arrays by defining the size of each array. The first array will be numbers, which will be one-dimensional and will be initialised here using curly brackets with 5 elements. The square brackets are empty; you can do this if you initialise the data with the curly bracket by assigning the values at declaration. Following the array declaration, we find out the size of the array by creating the size_of_number integer, which we use to get the number of elements in the array. The way we are doing that is by using the sizeof function, which returns the actual size of the array in memory (which would be 5 elements and multiplying the integer size which is 4 bytes) which should be 20 bytes. Inside the first sizeof, it should return the memory size of the array and then divide it with the return value of the second sizeof call, which will be the size of the int data type. When the calculations are complete, the answer is obviously going to be 5. The second array multinumbers, is a two-dimensional array which is declared without being assigned any values.
// INITIALISE THE NUMBERS ARRAY BY ASSIGNING VALUES
int numbers [] = { 5, 50, 33, 90 , 77 };
int size_of_number = (sizeof(numbers)/sizeof(int));
// INITIALISE THE MULTI-DIMENSIONAL ARRAY WITHOUT ASSIGNING ANY VALUES
int multinumbers [NUM_COL_ROWS][NUM_COL_ROWS];
int i=0, r;
After the arrays, we declare the i, and r integer variables, as they will be used for looping. Now we are ready for the main course, we will first deal with a simple loop, which displays the values of the elements using printf.
// FIRST DO A SIMPLE PRINT OF THE FIRST ARRAY'S DATA
printf("The Numbers Array will now print it's Data\n");
for(;i < size_of_number; i++)
printf("Number - Element [%d] : %d\n", i, numbers[i]);
Moving on to the multi-dimensional array; the thing we are going to be doing here is using the array inside two nested for loops. The first one as you can see deals with the rows; that is using the r variable within the loop condition iterator. And inside that loop, you can see the next loop which uses the c variable inside this loop for the columns. Inside the nested loop, it will use the multinumbers array to assign a value, which is multiplying with the r and c values. Whilst doing this, you are filling out a 8x8 matrix with a maths times table. As the loops use the condition of less-than NUM_COL_ROWS, we will get the right results. When a value is assigned, then the code prints the data on the screen. We could have used another batch of nested loops to do the separate print method by using the array. But that would have led to unnecessarily verbose code.
// THEN DO THE TIMES TABLE USING THE MULTI-DIMENSIONAL ARRAY
printf("\nNow we are doing the times table using the Multi-Dimensional Array\n");
// LOOP FOR THE ROWS
for(r=0; r < NUM_COL_ROWS; r++)
{
printf("Row :");
// LOOP FOR THE COLUMNS
for(c=0; c < NUM_COL_ROWS; c++)
{
// DOING THE MULTIPLICATION FOR EACH CELL
multinumbers[r][c] = ((r+1) * (c+1));
printf("\t%d",multinumbers[r][c]);
}
printf("\n");
}
In more complex code, you will see more arrays, which will do more interesting tasks than these exercises. As you are aware of how they work and how important they are; working out how to do tasks with arrays will be no problem when such cases arise. All it needs to understand is patience, and most important practice.
Summary
With this tutorial, you have learnt how to use simple arrays. But as we have only worked with numeric arrays, we didn't deal with String Arrays, which will be dealt with in a later tutorial.