Loading, please wait...

Arrays

An array is a group of memory locations related to the fact that they all have the same name and the same type. To refer to a particular location or element in the array, we specify the name of the array and the position number of the particular element in the array.

 

The example shows an integer array called c. This array contains 12 elements. Anyone of these elements may be referred to by giving the name of the array followed by the position number of the particular element in square brackets ([]). The first element in every array is the zeroth element. Thus, the first element of array c is referred to as c[0], the second element of array c is referred to as c[1], the seventh element of array c is referred to as c[6], and, in general, the ith element of array c is referred to as c[i - 1].

 

Array names, like other variable names, can contain only letters, digits and underscores. Array names cannot begin with a digit. The position number contained within square brackets is more formally called a subscript (or index). A subscript must be an integer or an integer expression. If a program uses an expression as a subscript, then the expression is evaluated to determine the subscript.

 

For example,

if a = 5 and b = 6, then the statement,

c[ a + b ] += 2;

adds 2 to array element c[11]. A subscripted array name is an lvalue—it can be used on the left side of an assignment.

 

Let’s examine array c more closely. The array’s name is c. Its 12 elements are referred to as c[0], c[1], c[2], …, c[11]. The value stored in c[0] is  45, the value of c[1] is 6, the value of c[2] is 0, the value of c[7] is 62 and the value of c[11] is 78. To print the sum of the values contained in the first three elements of array c, we’d write

printf( "%d", c[ 0 ] + c[ 1 ] + c[ 2 ] );

 

 

 

To divide the value of the seventh element of array c by 2 and assign the result to the variable x, we’d write

x = c[ 6 ] / 2;

It’s important to note the difference between the “seventh element of the array” and “array element seven.” Because array subscripts begin at 0, the “seventh element of the array” has a subscript of 6, while “array element seven” has a subscript of 7 and is actually the eighth element of the array. This is a source of “off-by-one” errors.