Array in C

Array in C programming language is a collection of fixed size data belongings to the same data type. An array is a data structure which can store a number of variables of same data type in sequence. These similar elements could be of type int, float, double, char etc.

Properties of Array in C :

  • An array is a collection of same data types.
  • The size of array must be a constant integral value.
  • All elements of array are stored in the contiguous memory locations.
  • Single elements in an array can be accessed by the name of the array and an integer enclosed in square bracket called subscript/index variable like student[10].
  • Array is a random access data structure. you can access any element of array in just one statement.
  • The first element in an array is at index 0, whereas the last element is at index (size_of_array – 1).

Advantage of Array :

  • Less amount of code :Less code is used to access the data
  • Easy access of elements :By using the for loop, we can retrieve the elements of an array easily.
  • Easy for sorting :To sort the elements of the array, we need a few lines of code only.
  • Random Access :We can access any element randomly using the array.

Disadvantage of Array :

  • Fixed Size : We can not exceed the the limit size of array after it’s decleration.

Declaration of Array :

We can declare an array in the c language in the below given way.

data_type array_name[array_size];

Now, let us see the example to declare the array.

int marks[6];

Here, int is the data_type, marks are the array_name, and 6 is the array_size.

Initialization of Array :

We declare normal variables in c in the following ways :

int x;
x = 0;
int x = 0;

In the case of an array, simply list the array values in set notation { }. Some valid array declarations are shown below.

int num[6] = {2, 4, 6, 8, 10, 12};
char letters[6] = {‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’};
float numbers[3] = {9.04, 14.02, 7.3};

Array in C Example :

int main(){      
int i=0;    
int marks[5];//declaration of array       
marks[0]=10;//initialization of array    
//traversal of array    
printf("%d \n",marks[i]);    
}//end of for loop     
return 0;  

Output :

Declaration with Initialization in Array in C :

We can initialize the c array at the time of declaration. Let’s see the code.

int subjects[5]={20,30,40,50,60};

In such case, there is no requirement to define the size. So it may also be written as the following code.

int subjects[]={20,30,40,50,60};

Let’s see the C program to declare and initialize the array in C.

int main(){      
int i=0;    
int marks[3]={20,30,40};//declaration and initialization of array    
 //traversal of array    
printf("%d \n",marks[i]);    
return 0;  

Output :

Leave a Comment

Your email address will not be published. Required fields are marked *

// Sticky ads
Your Poster