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

Declaring an array means specifying the following:

  • Data type—the kind of values it can store, for example, int, char, float, double.
  • Name—to identify the array.
  • Size—the maximum number of values that the array can hold.

Arrays are declared using the following syntax:

datatype array_name[size];

For example, if we write,

int A[5];

The above syntax will declare an array of size 5. We can store 5 integer values in an array A. In C, the array index starts from zero. The first element will be stored in A[0], second element in A[1], and so on. Therefore, the last element, that is the 5th element, will be stored in A[4]. Note that 0, 1, 2, 3 written within square brackets are the subscripts.

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:

Copy to Clipboard

Accessing the elements of an Array

Copy to Clipboard