Array

An array is a collection of data items having the same data type.

All the data elements stored in the array is of same type like char, int, float, double. Data in the array can be accessed by index of an array and this index generally starts from 0 to n-1, where n is size of an array.

Types of Array:

  1. Single dimension array
  2. Multi dimension array

Declaration of Array:

int A[5];

The above syntax will declare an array of size 5. We can store 5 integer values in an array A.

Initialization of Array (static): 

int A[5] = {10,20,30,40,50};

array

Array

In above figure, 10 is stored at index 0, so it can be accessed as a[0], 20 can be accessed as a[1] and so on.

How to initialize array dynamically at run time with for loop in C language

Here we will see how to initialize array dynamically at run time using C programming. In above section we have seen how to initialize array statically in C code. But in many cases it is require to take input from users to store data in array at program run time in C language. For that we can use ‘for’ loop to accomplish this task as below:

C program to initialize array dynamically
Copy to Clipboard

The above program will declare array of size 10, indexed from 0 to 9. For loop with scanf statement will take elements one by one from user as input and store it in array a. Scanf statement will execute 10 times as we take condition j

Output:

enter element 0 : 10
enter element 1 : 20
enter element 2 : 30
enter element 3 : 40
enter element 4 : 50
enter element 5 : 60
enter element 6 : 70
enter element 7 : 80
enter element 8 : 90
enter element 9 : 100

Your array elements are : 10   20   30   40   50   60   70   80   90   100