Let’s take the concept of arrays to about compile time and run time initialization −
Array
Array is a collection of items stored at contiguous memory locations and elements can access by using indices.
Compile time array initialization
In compile time initialization, user has to enter the details in the program itself.
Compile time initialization is same as variable initialization. The general form of initialization of array is as follows −
Syntax
type name[size] = { list_of_values }; //integer array initialization int rollnumbers[4]={ 2, 5, 6, 7}; //float array initialization float area[5]={ 23.4, 6.8, 5.5,7.3,2.4 }; //character array initialization char name[9]={ 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', '\0' };
Example
Following is a C program to display array −
#include<stdio.h> void main(){ //Declaring array with compile time initialization// int array[5]={1,2,3,4,5}; //Declaring variables// int i; //Printing O/p using for loop// printf("Displaying array of elements :"); for(i=0;i<5;i++){ printf("%d ",array[i]); } }
Output
Displaying array of elements :1 2 3 4 5
Run time Array initialization
Using runtime initialization user can get a chance of accepting or entering different values during different runs of program.
It is also used for initializing large arrays or array with user specified values. An array can also be initialized at runtime using scanf() function.
Example
Following is a C program to calculate sum and product of all elements in an array using run time compilation −
#include<stdio.h> void main(){ //Declaring the array - run time// int A[2][3],B[2][3],i,j,sum[i][j],product[i][j]; //Reading elements into the array's A and B using for loop// printf("Enter elements into the array A: \n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ printf("A[%d][%d] :",i,j); scanf("%d",&A[i][j]); } printf("\n"); } for(i=0;i<2;i++){ for(j=0;j<3;j++){ printf("B[%d][%d] :",i,j); scanf("%d",&B[i][j]); } printf("\n"); } //Calculating sum and printing output// printf("Sum array is : \n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ sum[i][j]=A[i][j]+B[i][j]; printf("%d\t",sum[i][j]); } printf("\n"); } //Calculating product and printing output// printf("Product array is : \n"); for(i=0;i<2;i++){ for(j=0;j<3;j++){ product[i][j]=A[i][j]*B[i][j]; printf("%d\t",product[i][j]); } printf("\n"); } }
Output
Enter elements into the array A: A[0][0] :A[0][1] :A[0][2] : A[1][0] :A[1][1] :A[1][2] : B[0][0] :B[0][1] :B[0][2] : B[1][0] :B[1][1] :B[1][2] : Sum array is : 000 000 Product array is : 000 000