Array Initialization in C Programming

Initialization of Array in C programming language. Arrays in C programming language is not initialized automatically at the time of declaration. By default, array elements contain garbage value. Like any other variable in C, we can initialize arrays at the time of declaration.

Array Initialization by Specifying Array Size

int score[7] = {5,2,9,1,1,4,7};

Initialization of array after declaration.

int score[7];
score[0] = 5;
score[1] = 2;
score[2] = 9;
score[3] = 1;
score[4] = 1;
score[5] = 4;
score[6] = 7;

Array Initialization Without Specifying Array Size

int score[] = {5,2,9,1,1,4,7};

In above declaration, compiler counts the number Of elements inside curly braces{} and determines the size of array score. Then, compiler will create an array of size 7 and initialize it with value provided between curly braces{} as discussed above.

C Program to show Array Initialization

Array Initialization in C Programming

#include <stdio.h>
#include <conio.h>
 
int main(){
    /* Array initialization by specifying array size */
    int roll[7] = {1,2,3,4,5,6,7};
    /* Array initialization by without specifying array size */
    int marks[] = {5,2,9,1,1,4,7};
    int i;
    /* Printing array elements using loop */
    printf("Roll_Number   Marks\n");
    for(i = 0; i < 7; i++){
        printf("%5d   %9d\n", roll[i], marks[i]);
    }
     
    getch();
    return 0;
}

Output

Roll_Number   Marks
    1           5
    2           2
    3           9
    4           1
    5           1
    6           4
    7           7