Two Dimensional Array in C

In C or other programming languages, the two dimensional array is also called a matrix. It is also possible for arrays to have two or more dimensions.

Multidimensional arrays have two indexes values which specify the element in the array is called Two Dimensional Array in C.

For example: multi[i][j], where [i] specify row and [j] specify column.

Declaration of Two Dimensional array in C

You can declare an array of two dimensions as follows:

variable type array name[size1][size2]

In the above example, the variable type is the name of some type of variable, such as int. Also, size1 and size2 are the sizes of the array’s first and second dimensions, respectively.

Initialization of Two Dimensional array in C

int stud[4][2] = { {12, 13}, {21, 31}, {22, 33},{11,23}};
or 
int arr[2][3] = {12, 23, 34, 45, 56, 45};
or 
int arr[][3] = {12, 23, 34, 45, 56, 45};

Note: While initializing a 2-D array, it is necessary to mention the second(column) dimension, whereas the first dimension(row) is optional.

Programs:-

  1. A program that stores roll numbers and marks obtained by a student side by side in a matrix.
main( )
{ 
int stud[4][2] ; 
int i, j ; 
for ( i = 0 ; i <= 3 ; i++ ) 
{ 
printf ( "\n Enter roll no. and marks" ) ; 
scanf ( "%d %d", &stud[i][0], &stud[i][1] ) ; 
} 
for ( i = 0 ; i <= 3 ; i++ ) 
printf ( "\n%d %d", stud[i][0], stud[i][1] ) ; 
} 

There are two parts to the program in the first part through a for loop we read in the values of roll no. and marks, whereas, in the second part through another for loop we print out these values.

Recommended Post: