Two-Dimensional Array in C

The array which is used to represent and store data in a tabular form is called as Two Dimensional Array. Such type of array specially used to represent data in a matrix form. To declare Two Dimensional Array in C, the general syntax is as follows:

<data-type> <Array-name> [<rows>][<columns>];

The rows and columns, both must be integer constants greater than zero and data-type can be any valid C data type; primary or user-defined. For example, to declare a two dimensional array called StudentsMarks of type double and having 3 rows and 4 columns, we can use following statement:

double StudentMarks [3][4];

In order to initialize this array, we have two ways:

1. Initialize all elements at a time during declaration,

2. Initialize elements individually after declaration

The first method can be used to declare and assign values to all elements of 1D array as follows:
double StudentMarks [3][2] =
{
{0.0, 0.1},
{1.0, 1.1},
{2.0, 2.1}
};

Recall that to access any individual array element, the array name along with index within square braces is used, and it can be used the same way any other variable of same data type can be. However, in case of 2-D arrays we have use another dimensional also. This means element StudentMarks[0][0], which is the first element will be assigned value 0.0, second element StudentMarks[0][1] will be assigned value 0.1, third element StudentMarks[1][0] will be assigned value 1.0, fourth element StudentMarks[1][1] will be assigned value 1.1, and last element StudentMarks[2][1] will be assigned value 2.1.

It should be noted that the number of values between braces { } can’t be larger than the number of elements (rows x columns). However, if we omit the size of the array during declaration, an array just big enough to hold the values of initialization, is declared. Therefore, the following statement has same effect as the first valid statement above has.

double StudentMarks [][] =
{
{0.0, 0.1},
{1.0, 1.1},
{2.0, 2.1}
};

The second method is to assign values to every element individually. After declaration of StudentMarks array, we can initialize it as follows:
double StudentMarks [3][2];
StudentMarks[0][0] = 0.0;
StudentMarks[0][1] = 0.1;

StudentMarks[1][0]  = 1.0;
StudentMarks[1][1]  = 1.1;
StudentMarks[2][0]  = 2.0;
StudentMarks[2][1]  = 2.1;

Following is the pictorial representation of the same array we discussed above:

Screenshot from 2020-07-20 10-29-05

Program 1 shows how to read and display a 3×3 matrix using 2D array. It is followed by the output of the program.

#include <stdio.h>
void main()
{
int a[3][3], i, j;
printf(“Enter matrix of 3*3 : “);
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“\nMatrix is : \n”);
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf(“\t %d”,a[i][j]);
}
printf(“\n”);
}
}

Program 1: Program to read and display a 3×3 matrix using 2D array

Screenshot from 2020-07-20 10-31-29