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:
Array | Index range |
---|---|
int Exam_Mark[32]; | 0..31 |
char Line_Text[80]; | 0..79 |
int Card_Value[5]; | 0..4 |
#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.