Multi-Dimensional Arrays
As mentioned in the Previous post An array is a collection of Homogeneous Data Elements (Elements of same datatype).
An array with more than one dimension (array of arrays) are known as Multi-Dimensional array.Let us discuss Multi-Dimensional arrays with an example.
Two-Dimensional Array
An Array of One-Dimensional arrays.Here also the indices of the array starts from 0.
Let us consider a class of ten students and we have to store the percentages of those 10 students. An one-dimensional array with size 10 is enough to solve this problem.If there are two or more such classes and if we need to store the percentages of all the students of all those classes then we need to make use of Multi-Dimensional array (2d array) in such a way that one dimension is used to store the class and another is to store the percentage of students. If we observe clearly Two-Dimensional array is an array of One-Dimensional arrays. Above problem is solved by taking one dimensional arrays for storing percentages of each class and making those arrays as a Two-Dimensional Array (array of those one-dimensional arrays).
Syntax for declaring Two-Dimensional Arrays
datatype array_name[row_size][column_size];
Example:
float percentage[3][10];
Syntax Initializing Two-Dimensional Arrays
datatype array_name[max_row_size][max_col_size]={{val1,val2...valN},{val1,val2...valN}};
Example:
float percentage[5][5]={{63.2,72.3},{67,89}};
Note:
We cannot initialize Two-dimensional array without specifying its maximum size as in One-Dimensional arrays.If we try to do so compiler will generate an error "Size of the type is unknown or zero" as follows
Reading and Printing of Two-Dimensional Arrays
For Reading and printing of a Two-Dimensional array requires two loop statements,one controls rows and other controls columns.We can access the element of our interest by using indices.Program for reading and printing Two-Dimensional Array is given below
#include<stdio.h>
void main()
{
int i,j,a[5][5];
//Reading of a Two-Dimensional Array
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("Enter a[%d][%d]",i,j);
scanf("%d",&a[i][j]);
}
}
printf("\n");
//Printing of a Two-Dimensional Array
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
}
Output:
Two Dimensional Arrays are used to perform operations on Matrices.
0 comments:
Post a Comment