Two Dimensional (2D) Array in C

Two Dimensional (2D) Array in C


For the above 2D array we have the number of rows=3 and number of columns=3, so we represent it as a 3×3 array or a 3×3 matrix.

A matrix can also have specifications like 3×42×1, etc. Let us learn more about the 2D arrays.


2. How to declare a 2D Array in C?

2D array needs to be declared so that the compiler gets to know what type of data is being stored in the array.

Similar to 1D array, a 2D array can also be declared as an intcharfloatdouble, etc. Here is how we declare a 2D array(here integer array):

2D array declaration

datatype arrayVariableName[number of rows] [number of columns]
int num[10][5]; 

The ‘int’ specifies that the data stored in the array will be of integer type.
‘num’ is the variable name under which all the data is stored.
[10] refers to the number of rows of the array and
[5] refers to the number of columns of the array.

This is also a static memory allocation, that is, we are allocating the array a size equal to 10 x 5, that is, in this array, we can store 10 x 5 = 50 number of elements.

The actual size it will occupy in memory will depend on the data type of the array i.e. (size of array = number of elements it can hold x Size of datatype).

The two brackets i.e. [][] specify that the array is two-dimensional.


3. How to initialize and store data in a 2D array in C?

2D array initialization can be done while declaring the array as well. In simple words, we can store certain elements in the array while writing the program i.e. we know which values this array will always store.

Here are a few examples of initializing a 2D array:

//or the format given below

int num[3][3]={{25,10,5},{4,6,13},{45,90,78}};

int num[3][3]={{25,10,5}, //row0

{4,6,13}, //row1

{45,90,78} //row2

};

//this format also stores data in the array but results in a loss of readability

int num[2][4]={4,6,8,10,3,5,7,9};

Another important fact is that when initializing a 2D arrayspecifying the number of rows of the array is optional but specifying the number of columns of the array is important and mandatory.

Like a 1D array, the user can also input the values in the array using a for loop. The only difference is that we use a nested for loop for inserting the elements in a 2D array.