Arrays in C

When we work with a large number of data values we need that any number of different variables. As the number of variables increases, the complexity of the program also increases and so the programmers get confused with the variable names. There may be situations where we need to work with a large number of similar data values. To make this work easier, C programming language provides a concept called "Array". 

An array is a special type of variable used to store multiple values of same data type at a time. 

Array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations.

By using the array, we can access the elements easily. Only a few lines of code are required to access the elements of the array.

Declaration of an Array
 
We can declare an array in the c language in the following way.
 
data_type arrayName [ array_size ] ;  
 
Now, let us see the example to declare the array.
 
int a [3];
 
Here, the compiler allocates 6 bytes of contiguous memory locations with a single name 'a' and tells the compiler to store three different integer values (each in 2 bytes of memory) into that 6 bytes of memory. For the above declaration, the memory is organized as follows...
 
 
 
In the above memory allocation, all the three memory locations have a common name 'a'. So accessing individual memory location is not possible directly. Hence compiler not only allocates the memory but also assigns a numerical reference value to every individual memory location of an array. This reference number is called "Index" or "subscript" or "indices". Index values for the above example are as follows...
 

 
Accessing Individual Elements of an Array

The individual elements of an array are identified using the combination of 'arrayName' and 'indexValue'. We use the following general syntax to access individual elements of an array...

arrayName [ indexValue ] ;


For example, if we want to assign a value to the second memory location of above array 'a', we use the following statement...

a[1] = 100;


 


No comments:

Post a Comment