C Array Initialization

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

Questions


MaxPowersinty | 27-Dec-2018 11:44:01 pm

Download your missing dll from Error msvcr100.dll page. Fix the error now!


ShowSet | 18-Jan-2019 08:11:34 am

In year 2019 there are lot of films coming out. Obviously, there are Avengers part 2, new Star Wars Episode nine and many others. These are movies that every kid wants to see, but sometimes you can miss it.It is where applications come in handy you can watch a movies for free. Btw, looking for the best app to watch free movies on your Android phone? Then your should check Showbox app. This is the most famous app today that has a big library of shows and films. This app is also available for iMac users. But your need to download it first to enjoy free tv-shows Showbox for pc windows 10


KimerS | 05-Feb-2019 02:55:58 am

Interested in hardrock? How about Kiss band? The band is on a tour this 2019 year all across Canada and USA. Click on KISS Tour 2019 Canada to know more about KISS tour in 2019.


Ask Question