C

Array Initialization

After an array is declared it must be initialized. Otherwise, it will contain garbage value (any random value).
An array can be initialized at either compile time or at runtime.


1) Compile time Array initialization

Compile time initialization of array elements is same as ordinary variable initialization. The general form of initialization of array is,

Syntax:

type array_name[size] = { list_of_values };

//integer array initialization
int marks[4]={ 67, 87, 56, 77 };

//float array initialization
float area[3]={ 23.4, 6.8, 5.5 };

//character array initialization
char name[12]={ 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 'i', 'n', 'k', '\0' };

One important things to remember is that when you will give more initializer than declared array size than the compiler will give an error.

//Compile_time_error
int subject[2]={ 67, 87, 56, 77, 59 };

Example:

//Write a Program to initialize array at compile time.
#include<stdio.h>
#include<conio.h>
void main()
{
    int i;
    int arr[]={2, 3, 4};    //Compile time array initialization
    for(i=0; i<3; i++) {
        printf("%d ",arr[i]);
    }
    getch();
}

Output:

Command Prompt
2 3 4

2) Run time Array initialization

An array can also be initialized at runtime using scanf() function. This approach is usually used for initializing large array, or to initialize array with user specified values.

Example:

//Write a Program to initialize array at run time.
#include<stdio.h>
#include<conio.h>
void main()
{
    int arr[4];
    int i, j;
    printf("Enter array element:");
    for(i=0; i<4; i++)
    {
        scanf("%d",&arr[i]);    //Run time array initialization
    }
    printf("Value in Array:");
    for(j=0; j<4; j++)
    {
        printf("%d \n",arr[j]);
    }
    getch();
}

Output:

Command Prompt
Enter array element:
20
30
40
50
Value in Array:
20
30
40
50



Subscribe us on Youtube

Share This Page on


Ask Question