C array initialization

Syntax

C array initialization has the following format.

type arrayName[length] = {array elements};

Example - Initializing an array in declaration


#include <stdio.h>
#define SIZE 12/*w  w  w . j a v a2 s . c om*/

int main()
{
   int a[ SIZE ] = { 1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45 };
   int i; 
   int total = 0; 
   
   for ( i = 0; i < SIZE; i++ ) {
      total += a[ i ];
   } 

   printf( "Total of array element values is %d\n", total );
   
   return 0; 

} 

The code above generates the following result.

Example - Initializing an array using for loop


#include <stdio.h>
//from   www .ja  v  a  2s .  co  m
int main()
{
   int n[ 10 ]; 
   int i; 
   
   /* initialize elements of array n to 0 */
   for ( i = 0; i < 10; i++ ) {
      n[ i ] = 0;
   }
   
   printf( "%s%13s\n", "Element", "Value" );

   for ( i = 0; i < 10; i++ ) {
      printf( "%7d%13d\n", i, n[ i ] );
   } 

   return 0;

}

The code above generates the following result.





















Home »
  C Language »
    Language Basics »




C Language Basics
Data Types
Operator
Statement
Array