next up previous
Next: Functions Up: Arrays Previous: Activity

Array Initialization

C+= allows the initialization of arrays. The general form of array initialization is similar to that of other variables, as shown here:

type name[size]=value_list;

The value_list is a comma separated list of constants that are type compatible with the base of the array. The first constant will be placed in the first position of the array, the second constant in the second position and so on, notice that the semicolon follows the }. In the following example, a five element integer array is initialized.

int num[5]={5,3,8,10,32};

This means that num[0]=5, num[1]=3, num[2]=8, num[3]=10 and num[4]=32.

multidimensional arrays are initialized in the same way as one dimensional arrays. For example the following program initializes an array called cubes from number 1 through 5 and their cubes.

int cubes[5][2]={
1,1,
2,8,
3,27,
4,64,
5,125
};

Example

/* This program uses an initialized array to find the squares of a number entered by the user. It first looks up the number in the array and then prints the corresponding square. */

#include <iostream.h>

main()
{

int sqrs[10][2]={
1,1,
2,4,
3,9,
4,16,
5,25,
6,36,
7,49,
8,64,
9,81,
10,100
};

int i, j;

cout << "Enter a number between 1 and 10";
cin >>i;

for(j=0;j<10;j++)
if(sqrs[j][0]==i) break;
cout << "The square of " << i << "is";
cout << sqrs[j][1];
return 0;
}


next up previous
Next: Functions Up: Arrays Previous: Activity
Yousef Haik
2/23/1998