# C 2D Array

The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices which can be represented as the collection of rows and columns. However, 2D arrays are created to implement a relational database lookalike data structure. It provides ease of holding the bulk of data at once which can be passed to any number of functions wherever required.

## Declaration of two dimensional Array in C

The syntax to declare the 2D array is given below.

snippet
`data_type array_name[rows][columns];`

Consider the following example.

snippet
`int twodimen;`

Here, 4 is the number of rows, and 3 is the number of columns.

## Initialization of 2D Array in C

In the 1D array, we don't need to specify the size of the array if the declaration and initialization are being done simultaneously. However, this will not work with 2D arrays. We will have to define at least the second dimension of the array. The two-dimensional array can be declared and defined in the following way.

snippet
`int arr={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};`

### Two-dimensional array example in C

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

Output

Output
arr = 1 arr = 2 arr = 3 arr = 2 arr = 3 arr = 4 arr = 3 arr = 4 arr = 5 arr = 4 arr = 5 arr = 6

### C 2D array example: Storing elements in a matrix and printing it.

snippet
```#include <stdio.h>
void main ()
{
int arr,i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}```

Output

Output
Enter a: 56 Enter a: 10 Enter a: 30 Enter a: 34 Enter a: 21 Enter a: 34 Enter a: 45 Enter a: 56 Enter a: 78 printing the elements .... 56 10 30 34 21 34 45 56 78
Related Tutorial
Contents +