Two Dimensional ( 2D ) Arrays in C

Notes:

Two Dimensional ( 2D ) Arrays in C Programming Language:

2-Dimensional Arrays in C:
While accessing each element in an array; if it requires two indexes or subscripts such an array is called 2-dimensional array.
Ex: arrayName[index1][index2]

Note: 2D arrays are used to represent table of values i.e. values arranged in rows and columns

Declaring a two dimensional array:

Syntax:
data_type arrayName[rows][cols];

Ex:
int numbers[2][2]; // numbers is a 2D array, which can hold 2 rows and 2 columns of integer values

Getting a value of an array element:
We can get a value of an array element by its rindex and cindex.

Syntax:
arrayName[rindex][cindex]

Ex:
printf(“%d\n”,numbers[0][0]); // garbage integer value

Declaring and initializing a two dimensional array:

Syntax:
1. data_type arrayName[rows][cols] = {list of values separated by comma};
2. data_type arrayName[rows][cols] = {blocks of values separated by comma};

Ex:
1. int numbers[2][2] = {0,0,0,0};
2. int numbers[2][2] = {{0,0},{0,0}};

Setting a new value to an array element:
We can set a new value to an array element using assignment operator.

Syntax:
arrayname[rindex][cindex] = newvalue;

Ex:
numbers[0][0]=1;
printf(“%d\n”,numbers[0][0]); // 10

Example Code:

#include <stdio.h>

int main()
{
int numbers[2][2] = {
{0,0},
{0,0}
};

printf("%d\n",numbers[0][0]); // 0
printf("%d\n",numbers[0][1]); // 0
printf("%d\n",numbers[1][0]); // 0
printf("%d\n",numbers[1][1]); // 0
printf("\n");

numbers[0][0] = 1;
numbers[0][1] = 2;
numbers[1][0] = 3;
numbers[1][1] = 4;

printf("%d\n",numbers[0][0]); // 1
printf("%d\n",numbers[0][1]); // 2
printf("%d\n",numbers[1][0]); // 3
printf("%d\n",numbers[1][1]); // 4
printf("\n");

return 0;
}