# Two-Dimensional Array in C

In this lesson, you will learn about the two-dimensional array or 2D array, known as a matrix, the way it’s declared and initialized.

## 2D array in C

A 2D or two-dimensional array is an array of arrays, which takes the form of a table containing rows and columns. for example:

`int array[4][3];`

can be represented in this form

## Declaring a two-dimensional array in C

Here is how to declare a two-dimensional array in C:

`int array[5][3];`

The array above contains 15 values of integers.

## Initializing a two-dimensional array in C

`int my_array[5][2] = {{1, 3}, {1, 5},{3, 7},{4, 9},{2, 3}};`

## Example I of a two-dimensional array in C

```#include <stdio.h>
int main ()
{
int i = 0, j = 0;
int array[4][3] = { {2, 2, 1}, {4, 3, 5}, {3, 2, 1}, {2, 2, 6} };
for (i = 0; i < 4; i++)
{
for (j = 0; j < 3; j++)
{
printf ("array[%d][%d] = %d \n", i, j, array[i][j]);
}

}
return 0;
}```

Output

array[0][0] = 2
array[0][1] = 2
array[0][2] = 1
array[1][0] = 4
array[1][1] = 3
array[1][2] = 5
array[2][0] = 3
array[2][1] = 2
array[2][2] = 1
array[3][0] = 2
array[3][1] = 2
array[3][2] = 6

## Example II of a two-dimensional array in C

```#include<stdio.h>
int main(){

int Array[3][4];
// input values into array
int i, j;
for(i=0; i<3; i++) {
for(j=0;j<4;j++) {
printf("Please enter a value for Array[%d][%d]: ", i, j);
scanf("%d", &Array[i][j]);
}
}
// print out values to the console
printf("\n");
printf("2D array elements:\n");
for(i=0; i<3; i++) {
for(j=0;j<4;j++) {
printf("%d ", Array[i][j]);
if(j==3){
printf("\n");
}
}
}
return 0;
}```

Output

Please enter a value for Array[0][0]: 5
Please enter a value for Array[0][1]: 8
Please enter a value for Array[0][2]: 9
Please enter a value for Array[0][3]: 1
Please enter a value for Array[1][0]: 4
Please enter a value for Array[1][1]: 4
Please enter a value for Array[1][2]: 3
Please enter a value for Array[1][3]: 7
Please enter a value for Array[2][0]: 6
Please enter a value for Array[2][1]: 1
Please enter a value for Array[2][2]: 2
Please enter a value for Array[2][3]: 0

2D array elements:
5 8 9 1
4 4 3 7
6 1 2 0

## Points to remember

• A 2D array is an array of arrays
• You will need indexes to loop through a 2D array

Back to: Learn C Programming > Arrays in C