Home >>C Tutorial >C 2-Dimensional Array
The two-dimensional array or in short the 2D arrays in C language are generally defined as an array of arrays. The 2D array can be represented as the collection of rows and columns as they are organized as matrices. However, the main reason of the creation of the 2D arrays is to implement a relational database lookalike data structure. The 2D arrays avails the ease of holding the bulk of data all at once that can be passed to any number of functions wherever it is required.
Here is the syntax to declare the 2D array:
data_type array_name[rows][columns];
Here is a brief example to understand it:
int twodimen[3][4];
In the above mentioned example, 3 depicts the number of rows and 4 depicts the number of columns.
There is no need to specify the size of the array if the declaration and initialization both are being done at the same time in the 1D array. But, this case will not work with the 2D arrays. Users need to define at least the second dimension of the array. In order to declare and define the two-dimensional array follow the below mentioned syntax:
int arr[3][4]={{1,2,3,4},{2,3,4,5},{3,4,5,6}};
#include<stdio.h> int main() { int i=0,j=0; int arr[3][4]={{1,2,3,4},{2,3,4,5},{3,4,5,6}}; for(i=0;i<3;i++) { for(j=0;j<4;j++) { printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]); } } return 0; }
#include<stdio.h> int main() { int i=0,j=0; int arr[3][4]={{1,2,3,4},{2,3,4,5},{3,4,5,6}}; int sum=0; for(i=0;i<3;i++) { for(j=0;j<4;j++) { sum=sum+arr[i][j]; } } printf("Sum =%d ",sum); return 0; }
#include<stdio.h> int main() { int i=0,j=0; int arr[3][4]={{1,2,3,4},{2,3,4,5},{3,4,5,6}}; int even=0; int odd=0; for(i=0;i<3;i++) { for(j=0;j<4;j++) { if(arr[i][j]%2==0) { even=even+arr[i][j]; } else { odd=odd+arr[i][j]; } } } printf("Sum of even =%d \n",even); printf("Sum of odd =%d",odd); return 0; }