C programming language also support multidimensional arrays.
Syntax of multidimensional array declaration:
Data_type array_name[size1][size2]…[sizeN];
For example, if we want to creates a three dimensional integer array −
int num[5][10][4];
Two-dimensional Arrays
The simplest form of multidimensional array is the two-dimensional array.
if we want to declare a two dimensional integer array of size [x][y] ( where x is a number of rows and y is a number of columns ) you would write something as follows −
int a[3][4];
In the above line we have created two-dimensional integer array ”a” with 3 rows and 4 columns.
In a C programming language Multidimensional arrays may be initialized by specifying bracketed values for each row.
For example we want to create an integer array with 3 rows and each row has 4 columns.
1 2 3 4 5 | int a[3][4] = { { 1, 2, 3, 4 } , /* for row index 0 */ { 5, 6, 7, 8 } , /* for row index 1 */ { 9, 10, 11, 12} /* for row index 2 */ }; |
Above the nested braces indicates the intended rows.
The following initialization is equivalent to the previous example −
int a[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};
which indicate the nested braces for intended row, are optional.
Accessing Elements of Two-Dimensional Array
Create a two-dimensional array of size 3*3 and nested loop is used to handle a two-dimensional array −
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #include <stdio.h> int main () { /* an array with 3 rows and 3 columns*/ int a[3][3] = { {1,2,3}, {4,5,6}, {7,8,9}}; int i, j; /* output each array element's value */ for ( i = 0; i < 3; i++ ) { for ( j = 0; j < 3; j++ ) { printf("a[%d][%d] = %d\n", i,j, a[i][j] ); } } return 0; } |
1 2 3 4 5 6 7 8 9 | a[0][0] = 1 a[0][1] = 2 a[0][2] = 3 a[1][0] = 4 a[1][1] = 5 a[1][2] = 6 a[2][0] = 7 a[2][1] = 8 a[2][2] = 9 |
Example: Write a program to create 3*3 matrix and take all elements of matrix as an input from user and print it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | #include <stdio.h> int main () { /* an array with 5 rows and 2 columns*/ int a[3][3]; int i, j; printf("Enter 9 elements of 3*3 matrix in sequence"); for ( i = 0; i < 3; i++ ) /* input each array element's value */ { for ( j = 0; j < 3; j++ ) { scanf("%d", &a[i][j] ); } } printf("Elements of 3*3 matrix is \n"); /* output each array element's value */ for ( i = 0; i < 3; i++ ) { for ( j = 0; j < 3; j++ ) { printf("%d ", a[i][j] ); } printf("\n"); } return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Enter 9 elements of 3*3 matrix in sequence 21 32 33 44 35 23 56 45 31 Elements of 3*3 matrix is 21 32 33 44 35 23 56 45 31 |