A data item is stored in memory in one or more adjacent storage locations depending upon its type. An array is also known as a series of homogeneous pieces of data that are identical in type.
Suppose we have to read marks obtained by a student in 5 different subjects and calculate total and percentage. First, we declare 5 different variable to read marks on different subjects as,
int a, b, c, d, e, f;
Then we need to enter the marks of different subjects
printf("Enter marks of 5 subjects:");
Finally to calculate the total marks we have to write below statement,
total = (a+b+c+d+e+f);
If you have huge number of students then this will very very complex to define every time and calculate the total.
If you have collection of data’s then you can represent by using array, this will help you to make faster and easy to calculate and easy to define.
This will be the faster way to do the task. To declare array of integer for 5 subject we write as follows
This is the example of array, int is the data type of array, you can define float, double and other also as per your need, marks is the variable which can have the 5 different datas.
It is the index which start from 0 and it will allocate 5 different memory location on stack or memory. we can use loop to read 5 different data’s,
for(i=0; i<5; i++)
To declare an array in C, you have to specify the name of the data type and the number of elements inside the square brackets, i.e int marks;
Here int specifies the datatype of array i.e datatype may be int, float, and char etc, and the marks is the array name, it is just like a variable. The number inside the square bracket specifies the size of an array.
#define M 5
The #define M 5 is the constant variable which will be known as a macro. The marks to be an array containing 5 integer elements. Two-dimensional array declaration is type followed by an identifier with two square brackets with the positive integer value.
data_type identifier [number_of_rows][number_of_column]
You can define macro for the two-dimensional array,
#define M 10
#define N 20
int array[M][N] or int array