Arrays

An array is used to create a variable which can refer to a list of items. We can then either refer to the whole list or to one of its constituent items. Examples of such lists might be the marks awarded to students in an examination, the characters making up a line of text or the cards in a poker hand. In each case we know the items are all of the same type and we know a maximum number of items that may be present.

We declare an array as follows:

int Exam_Mark[32];
char Line_Text[80];
int Card_Value[5];
Notice that the form of these declarations is similar to those for simple variables, but now we add a number in square brackets after the identifier. This number specifies the number of items in the array. Thus we assume a class of 32 students, a line of up to 80 characters and 5 cards in a poker hand.

We can now access an item in an array by specifying the name of the array followed by a number enclosed in square brackets, known as an index value or subscript. This defines one particular item in the array and allows us to use it as a variable of the type contained in that array.

Note carefully that the index value must be within the range declared for that array and that this range always starts at zero. Thus the legal ranges for the arrays above are:
ArrayIndex range
int Exam_Mark[32];0..31
char Line_Text[80];0..79
int Card_Value[5];0..4
Here is an example of the use of an array. Notice how it combines well with a for loop.

#include <stdio.h>

/* read in and compare 2 strings */

#define TRUE  1
#define FALSE 0

void main()
{
    int I, Success;
    char Check[6], Found[6];

    for (I = 0; I<=5; I++) Check[I] = getchar();
    for (I = 0; I<=5; I++) Found[I] = getchar();
    Success = TRUE;
    for (I=0; I<=5; I++) if (Check[I]!=Found[I]) Success=FALSE;
    if (Success) printf("Match\n"); else printf("Mismatch\n");
}
Plain text to compile.

Exercises on this section.


Next.

Back to Contents page.