Home >>C Tutorial >C Arrays
The arrays in the C language are generally defined as the collection of similar type of data items that are stored at contiguous memory locations. The arrays are basically the obtained data type in the C programming language that can store the primitive type of data like: int, double, float, char, etc. The arrays in C also possess the capability of storing the collection of derived data types like: structure, pointers, etc. In the arrays in C, each data element can be accessed randomly by the use of its index number and the arrays are known to be the simplest data structure.
If the users have to store similar elements then in this case C arrays are proven to be most beneficial. For instance; let's take a case where a user want to store the marks of a student in 8 subjects then in this case the user don't need to define different variables for the marks in different subjects. Despite of doing that, the user can define an array that can store the marks in each subject at the contiguous memory locations.
The elements can be accessed easily by the use of arrays just by a few lines of code the users can access elements of the array.
Here are the properties contained in the arrays are listed below:
Here is the syntax by which the users can declare an array in the c language:
data_type array_name[array_size];
Examle of array declaration
int SubjectMarks[4];
The use of each element’s index is known to be the simplest way to initialize an array in the C language. Users can initialize each element of the array just by using the index.
//array initialization SubjectMarks[0]=60; SubjectMarks[1]=70; SubjectMarks[2]=80; SubjectMarks[3]=95;
#include<stdio.h> int main() { int i=0; //array declaration int SubjectMarks[4]; //array initialization SubjectMarks[0]=60; SubjectMarks[1]=70; SubjectMarks[2]=80; SubjectMarks[3]=95; //Display all Subject marks for(i=0;i<4;i++) { printf("%d ",SubjectMarks[i]); } return 0; }
The C array can be initialized at the time of declaration, here is the code:
int SubjectMarks[4]={10,20,56,98}
In the above mentioned type of cases, there is no need to define the size hence, it can also be written as the code given below:
int SubjectMarks[]={10,20,56,98}
#include<stdio.h> int main() { int i=0; //array initialization int SubjectMarks[4]={60,70,80,95}; //Display all Subject marks for(i=0;i<4;i++) { printf("%d ",SubjectMarks[i]); } return 0; }
#include<stdio.h> int main() { int i=0; int num[5]={10,20,30,40,50}; int sum=0; for(i=0;i<4;i++) { sum=sum+num[i]; } printf("Sum=%d ",sum); return 0; }
#include<stdio.h> int main() { int i=0; int num[6]={10,11,12,13,14,15}; int even=0; int odd=0; for(i=0;i<6;i++) { if(num[i]%2==0) { even=even+num[i]; } else { odd=odd+num[i]; } } printf("Sum of even=%d \n",even); printf("Sum of odd=%d",odd); return 0; }