Array initialization

 

    int grades[5]={98,97,75,89, 100};

    char vowels[5]={ 'a' , 'e', 'i' ,'o' , 'u' };

    float salary[4]={200.5 , 300.0 , 450, 350 , 740 };

grades value 98 97 75 89 100
index 0 1 2 3 4

 

White space

 

Because white space is ignored in C , initializations may be continued across multiple lines . Example

    int gallons [9] = { 12, 34, 9, 

                                34, 56, 78,

                                 90,22,34}; 

 

Partial initialize

 

If the number of initializers is less than the declared number of elements listed in square brackets , the initializers are applied starting with array element 0.The remaining elements are automatically initialized to 0. (avg[3] will be initialized with zero).

    float avg[4]= {1.2 , 4.5 , 3.2};

 

zero initialization

 

To initialize an array to zero use:

 

for(int i=0; i<4; i++)

      avg[i]=0.0;

 

OR FASER WAY

 float avg[4]={0.0};

 

which explicitly initialize the first element to zero and initialize the remaining 3 elements to zero , because there are fewer initializers than there are elements in the array. Arrays are not automatically initialized to zero. This method of initializing the array elements to zero is performed at compile time for static arrays and at run time for automatic arrays.

 

Omit Array size

 

A unique feature of initializers is that the size of an array may be omitted when initializing values. Only the dimension is omitted; the brackets [] remain to indicate the definition of an array. The following 2 declarations are equivalent:

     int amounts[3]={3,6,7};    // array of size 3

     int amounts[]={3,6,7};       // array of size 3

   

We can also use :

      char codes[]="sample";           /*no braces or commas*/