int i1,i2,i3,i4,i5;
What if you wanted to declare 100 variables? That would take quite a long time. If you use an array on the other hand then you can declare as many variables as you want with only 1 variable name.
An array is declared in the same way as a normal variable except that you must put square brackets after the variable name. You must also put the amount of elements you want in the array in these sqaure brackets.
int a[5];
...
To access the value of an element of an array you must again use the square brackets but with the number of the element you want to access. When accessing an element of an array you must remember that they start from 0 and not 1. This means that an array which has 5 elements has an element range of 0 to 4.
int a[5];
a[0] = 12;
a[1] = 23;
a[2] = 34;
a[3] = 45;
a[4] = 56;
printf("%d",a[0]);
Using arrays with loops
The most useful thing to do with an array is use it in a loop. This is because the element number follow a sequence just like a loop does.When an array is declared the values are not set to 0 automatically. You will sometimes want to set the values of all elements to 0. This is called initializing the array. Here is an example of how to initialize an array of 10 elements using a for loop:
int a[10];
for (i = 0;i < 10;i++)
a[i] = 0;
Multi-dimensional arrays
The arrays we have been using so far are called 1-dimensional arrays because they only have what can be thought of a 1 column of elements. 2-dimensional arrays have rows and columns. Here is a picture which explains it better:1-dimensional array
0 | 1 |
---|---|
1 | 2 |
2 | 3 |
0 | 1 | 2 | |
---|---|---|---|
0 | 1 | 2 | 3 |
1 | 4 | 5 | 6 |
2 | 7 | 8 | 9 |
int a[3][3],i,j;
for (i = 0;i < 3;i++)
for (j = 0;j < 3;j++)
a[i][j] = 0;
0 comments:
Post a Comment