Arrays

Often instead of having a single item of data, you will have a list of data items of the same type. For instance, you may have a list of the names of all the students in a class, or the grades they got on their last test. It would be possible to store all of this data in separate variables, but this would be difficult to work with. Arrays allow you to store a number of items of the same type in one data structure. Each item is given its own index and so can be manipulated independently of all other items. In short, an array is a list of items.

Arrays can be declared as follows:


<type> <arrayName>[<size of array>];
For example, an array that holds five integers could be declared as:
int grades[5];

It should be noted that in C, indices always start at 0, so the array grades has the following five integers in it:
grade[0]
grade[1]
grade[2]
grade[3]
grade[4]

The following code snippet shows how an array might be used in practice:

int main()
{
    int grade[5];
    int i, sum = 0;
    float average;

    grade[0] = 43;
    grade[1] = 92;
    grade[2] = 53;
    grade[3] = 37;
    grade[4] = 73;

    for(i = 0; i< 5; i++)
    {
        sum = sum + grade[i];
    }
 
    average = sum / 5.0;

    return 0;
}

next


 home                      table of contents                      about