Array
In C language array is defined as the collection of similar types of data items stored at contiguous memory location. In array we can store the primitive type of data such as int, char, double , float etc. Array has the capability to store the collection of derived data type such as structure, pointers etc. In the array we can access the elements easily.
- Each element of an array is same data type and carries the same size, int=4 bytes.
- When we have a small number of object we store easily but we want to store a large number of instances it become difficult to manage them with normal variable but in the array is to represent many instances in one variable.
Advantage of array
- In array less code to the access the data.
- In array we can easily sort the element,we need a few lines of code only.
- We can access any element randomly using the array.
Disadvantage of array
- We define the size of the array at the time of declaration of the array then we can’t exceed the limit.
- Insertion and deletion of elements can be costly since the elements are needed to be managed in accordance with the new memory allocation.
Declaration of Array
We can declare an array in C language
data_type array_name[array_size];
Let’s see the example to declare the array.
int marks[10];
Initialization of array
Initialize array by using the index of each element. we can initialize each element of the array by using the index.
Consider the following example
marks[0]=10;
marks[1]=20;
marks[2]=30;
marks[3]=40;
marks[4]=50;
Array Example
#include<stdio.h> int main(){ int i=0; int marks[5]; marks[0]=10; marks[1]=20; marks[2]=30; marks[3]=40; marks[4]=50; for(i=0;i<5;i++){ printf("%d \n",marks[i]); } return 0; }
Output
10 20 30 40 50
Let’s see the C program to declare and initialize the array.
#include<stdio.h> int main(){ int i=0; int marks[5]={10,20,30,40,50}; for(i=0;i<5;i++){ printf("%d \n",marks[i]); } return 0; }
Output
10 20 30 40 50
Submit your review | |