Loading, please wait...

Array Definition

Arrays occupy space in memory. You specify 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 definition

int c[ 12 ];

is used. The following definition

int b[ 100 ], x[ 27 ];

reserves 100 elements for integer array b and 27 elements for integer array x. Arrays may contain other data types. For example, an array of type char can be used to store a character string.

 

Array Examples

This section presents several examples that demonstrate how to define arrays, how to initialize arrays and how to perform many common array manipulations.

Defining an Array and Using a Loop to Initialize the Array’s Elements uses for statements to initialize the elements of a 10-element integer array n to zeros and print the array in a tabular format. The first printf statement displays the column heads for the two columns printed in the subsequent for the statement.

 

Example

* initializing an array */
#include <stdio.h>

Int main(void)
{
int n[ 10 ]; /* n is an array of 10 integers */
int i; /* counter */
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ ) {
n[ i ] = 0; /* set element at location i to 0 */
} /* end for */

printf( "%s%13s\n", "Element", "Value" );
/* output contents of array n in tabular format */
for ( i = 0; i < 10; i++ ) {
printf( "%7d%13d\n", i, n[ i ] );
} /* end for */

return 0;
}

 

Output:

 Element          Value

   0                0

   1                0

   2                0

   3                0

   4                0

   5                0

   6                0

   7                0

   8                0

   9                0