One Dimensional Array In C Language


Array Definition

Arrays are the derived data type and it can store the primitive type of data such as int, char, double, float, etc. But you can't store different types in a single array.

Arrays are a way to store a list of items. Each slot of the array holds an individual element, and you can place elements into or change the contents or those slots as you need to.

1-D Array Declaration

We can declare an array in C using subscript operator.

 data_type array_name[array_size]; 

An array is declared in the same manner as ordinary variables, except that each array name must be accompanied by a size specification. This is necessary because the compiler will have to know how much memory to reserve for this array.


Advantage of Array

Code Optimization: It makes the code optimized; we can retrieve or sort the data easily.

Random access: We can get any data located at any index position.

Less amount of code: Using array we can aggregate N variables of same data type in a single data structure. Otherwise we have to declare N individual variables.

Easy access of elements: We can access any element of array using array name and index. We can access all elements serially by iterating from index 0 to size-1 using a loop.

Initialization of C Array

An array can be initialized when declared by specifying the values of some or all of its elements. Arrays can be initialized at the time of declaration when their initial values are known in advance.

The values to initialize an array must be constants never variables or function calls. The array can be initialized as follows:

 int array[5] = {4,5,7,2};

 float x[6] = {0,2.5,0,0.50,0,0};



 value of arr[0] is 10
 value of arr[1] is 20
 value of arr[2] is 30
 value of arr[3] is 40
 value of arr[4] is 50