Initializing Arrays

It is possible to assign values to array elements when you declare the array. Some examples will show the syntax:
int score[6] = {95, 73, 80, 88, 79, 92};
float weight[3] = {4.5, 3.45, 18.5};
char grade[] = {'A', 'B', 'C', 'D', 'F'};
Notice that the last example didn't specify the size of the array. This is because the compiler can figure it out by counting the number of initializers in the list.

If the number of initializers is less than the specified size of the array, the remaining elements are initialized to zero.
int score[6] = {95, 73, 80, 88};
float weight[3] = {4.5};
char grade[5] = {'A', 'B', 'C', 'D'};
The unspecified elements are set as follows:
score[4] = 0;
score[5] = 0;
weight[1] = 0.0;
weight[2] = 0.0;
grade[4] = 0;
Previous page
Next page

Back to Lesson 11 Index
Back to Outline