Arrays occupy space in memory. The programmer specifies the type of each element and the number of elements required by each array so that the computer may reserve the appropriate amount of memory. To tell the computer to reserve 12 elements for integer array c, the declaration
int c[ 12 ];
is used. Memory may be reserved for several arrays with a single declaration. To reserve 100 elements for integer array b and 27 elements for integer array x, the following declaration is used:
int b[ 100 ], x[ 27 ];
Arrays may be declared to contain other data types. For example, an array of type char can be used to store a character string.
Example: The following code uses a for repetition structure(loop) to initialize the elements of a 5-element integer array n to zeros and prints the array in tabular format.
#include <stdio.h> int main() { int n[ 5 ], i; for ( i = 0; i <= 4; i++ ) n[ i ] = 0; /* initialize array */ printf( "%s%13s\n", "Element", "Value" ); for ( i = 0; i <5; i++ ) /* print array */ printf( "%7d%13d\n", i, n[ i ] ); return 0; } Output: Element Value 0 0 1 0 2 0 3 0 4 0
The elements of an array can also be initialized in the array declaration by following the declaration with an equal sign and a comma-separated list (enclosed in braces) of initializers.
#include <stdio.h> #define MAX 5 /* Is equal to MAX = 5*/ int main() { int n[ MAX] = { 32, 27, 64, 18 }; /* Initializing the array. */ int i; printf( "%s%13s\n", "Element", "Value" ); for ( i = 0; i <= MAX; i++ ) printf( "%7d%13d\n", i, n[ i ] ); return 0; }
Note: If there are fewer initializers than elements in the array, the remaining elements are initialized to zero. For instance, in the following array n[4], the last element has value of 0 int n[ 5] = { 32, 27, 64, 18 };
But, if there are fewer elements than initializers, it’s an error. For instance, this will bring an error, int n[ 5] = { 32, 27, 64, 18,21,10 };