PPS Array
PPS Array
An array is defined as the collection of similar type of data items stored at contiguous memory locations.
Arrays are the derived data type in C programming language which can store the primitive type of data such as
int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as
pointers, structure, etc.
The array is the simplest data structure where each data element can be randomly accessed by using its index
number.
FEATURES OF ARRAY
• Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
• Elements of the array are stored at contiguous memory locations.
• Elements of the array can be randomly accessed with the given base address and the size of the element.
ADVANTAGE OF C ARRAY
1) Code Optimization: Less code to the access the data.
2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
DECLARATION OF C ARRAY
We can declare an array in the c language in the following way.
data_type array_name[array_size];
>>example to declare the array.
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is the array_size.
INITIALIZATION OF C ARRAY
The simplest way to initialize an array is 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]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
int marks[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 marks[]={20,30,40,50,60};
C ARRAY EXAMPLE
#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
}
OUTPUT
80
60
70
85
75
example
int twodimen[4][3];
INITIALIZATION OF 2D ARRAY IN C
We will have to define at least the second dimension of the array. The two-dimensional array can be declared
and defined in the following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};