Friday 6 March 2015

Multidimensional Arrays in C

The type of arrays that we discussed up to now is called a one-dimensional (or single dimensional) array, as it takes one index and store only one type of data. The array that was used in Program-6.1 hold only marks of one student. It can be extended to store marks of many students using a twodimensional array. Such an array is declared in the following form:

data-type array-name[size-1][size-2];
 
You can declare an array to hold marks of 100 students with store marks of 5 subjects as in the following example:

int students[100][5];
 
The first index defines the number of students and the second index defines the number of subjects. Altogether it declares 500 (100´5) memory locations. Initialising marks of the first student can be performed in the following manner.

Marks[0][0] = 55;
marks[0][1] = 33;
marks[0][2] = 86;
marks[0][3] = 81;
marks[0][4] = 67;

Similarly we can define arrays with n dimensions and such arrays are called n-dimensional or multidimensional arrays.

A two-dimensional array is initialised in the same way. The following statement declares and initialises a two-dimensional array of type int which holds the scores of three students in five different tests.

int students[3][5]= {
{55, 33, 86, 81, 67},
{45, 46, 86, 30, 47},
{39, 82, 59, 57, 60}
};
 
Exercise 6.1 – Write a program to store marks of 5 students for 5 subjects given through the keyboard. Calculate the average of each students marks and the average of marks taken by all the students.

No comments:

Post a Comment