C Initializing 1-D Array



Different Methods of Initializing 1-D Array

Whenever we declare an array, we initialize that array directly at compile time.

Initializing 1-D Array is called as compiler time initialization if and only if we assign certain set of values to array element before executing program. i.e at compilation time.

Initializing 1-D Array

Here we are learning the different ways of compile time initialization of an array.

Ways Of Array Initializing 1-D Array :

  1. Size is Specified Directly
  2. Size is Specified Indirectly

A. Method 1 : Array Size Specified Directly

In this method , we try to specify the Array Size directly.

int num[5] = {2,8,7,6,0};

In the above example we have specified the size of array as 5 directly in the initialization statement.Compiler will assign the set of values to particular element of the array.

num[0] = 2
num[1] = 8
num[2] = 7
num[3] = 6
num[4] = 0

As at the time of compilation all the elements are at Specified Position So This Initialization Scheme is Called as “Compile Time Initialization“.

Graphical Representation :

C Programming Array 1-D

B. Method 2 : Size Specified Indirectly

In this scheme of compile time Initialization, We does not provide size to an array but instead we provide set of values to the array.

int num[] = {2,8,7,6,0};

Explanation :

  1. Compiler Counts the Number Of Elements Written Inside Pair of Braces and Determines the Size of An Array.
  2. After counting the number of elements inside the braces, The size of array is considered as 5 during complete execution.
  3. This type of Initialization Scheme is also Called as “Compile Time Initialization

Sample Program

#include <stdio.h>

int main()
{
int num[] = {2,8,7,6,0};
int i;

for(i=0;i<5;i++) {
    printf("\nArray Element num[%d] : %d",i+1,num[i]);
}
    
return 0;
}

Output :

Array Element num[1] : 2
Array Element num[2] : 8
Array Element num[3] : 7
Array Element num[4] : 6
Array Element num[5] : 0