Thursday, November 24, 2011

Learn C programming tutorial lesson 6 - Arrays

Up until now if you wanted to declare 5 variables you would have to do something like this:
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
01
12
23
2-dimensional array
012
0123
1456
2789
You do get 3-dimensional arrays and more but they are not used as often. Here is an example of how you declare a 2-dimensional array and how to use it. This example uses 2 loops because it has to go through both rows and columns.
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

Setec Institute || Group : SH6 | | Name : Kim Chanthy. Powered by Blogger.

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Hot Sonakshi Sinha, Car Price in India