In this C programming language tutorial, we are going to talk about arrays.
An array lets you declare and work with a collection of values of the same type. Let’s say you want to declare four integers. With the knowledge from the last few tutorials you would do something like this:
int a , b , c , d;
What if you wanted to declare a thousand variables? That will take you a long time to type. This is where arrays come in handy. An easier way is to declare an array of four integers:
int a[4];
The four separate integers inside this array are accessed by an index. Each element can be accessed by using square brackets with the element number inside. All arrays start at element zero and will go to n-1. (In this case from 0 to 3). So if we want to fill each element you get something like this:
int a[4];
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 4;
If you want to use an element, for example for printing, you can do this:
printf("%d", a[1]);
Arrays and loops
One of the nice things about arrays is that you can use a loop to manipulate each element. When an array is declared, the values of each element are not set to zero automatically. In some cases you want to “initialize” the array (which means, setting every element to zero). This can be done like in the example above, but it is easier to use a loop. Here is an example:
#include<stdio.h>
int main()
{
int a[4];
int i;
for ( i = 0; i < 4; i++ )
a[i] = 0;
for ( i = 0; i < 4; i++ )
printf("a[%d] = %d\n", i , a[i]);
return 0;
}
Multi-dimensional arrays
The arrays we have been using so far are called one-dimensional arrays.
Here is an example of an one-dimensional array:
Here is an example of an one-dimensional array:
int a[2];
0
| 1 |
1
| 2 |
Note: A one-dimensional array has one column of elements.
Two-dimensional arrays have rows and columns. See the example below:
int a[2][2];
0
|
1
| |
0
| 1 | 2 |
1
| 4 | 5 |
Note: a[0][0] contains the value 1. a[0][1] contains the value 2. a[1][0] contains the value 4. a[1][1] contains the value 5.
So let’s look at an example that initialize a two-dimensional array and prints each element:
#include<stdio.h>
int main()
{
int a[4][4], i , j;
for (i = 0; i < 4; i++)
{
for ( j = 0; j < 4; j++)
{
a[i][j] = 0;
printf("a[%d][%d] = %d \n", i, j, a[i][j]);
}
}
return 0;
}
Note: As you can see, we use two “for loops” in the example above. One to access the rows and the other to access the columns.
A last word before we end this tutorial. The language C has no range checking, so if you index (choose an element) past the end of the array, it will not tell you. Instead the program will give you garbage data or it will crash.