Multi-Dimensional Arrays in C
In this article you will learn about multidimensional array and how to initialize and access the elements of an array in your C program.
Multi Dimensional Arrays in C
The simplest form of multidimensional array is the two-dimensional array. A two-dimensional array is pretty much a list of one-dimensional arrays.
The basic form of declaring a two-dimensional array of size x, y:
Syntax
data_type array_name[x][y];
array_name can be a valid C identifier. A two-dimensional array can be considered as a table with ‘x’ number of rows and ‘y’ number of columns.
Initializing Two-Dimensional Arrays
Two dimensional arrays in C can be initialised by two different methods.
Direct Method:
int x[3][3] = {0, 1 ,2 ,3 ,4 , 5 , 6 , 7 , 8 }
This array has 3 rows and 3 columns. The elements in the braces from left to right are stored in the table also from left to right. The elements will be filled in the array in the order, first 3 elements from the left in first row, next 3 elements in second row and goes on.
Nested braces Method:
int x[3][4] = {{0,1,2}, {3,4,5}, {6,7,8}};
Nested braces can be used to initialize multidimensional arrays. Each set of inner braces represents one row.
Accessing Elements of Two-Dimensional Arrays
Elements in a Two-Dimensional array can be accessed using the row indexes and column indexes.
int x[1][2];
The above example represents the element present in first row and second column.
SourceCode
Sample program to print the elements of a two dimensional array
[maxbutton id=”1″ url=”https://coderseditor.com/?id=224″ ]
#include<stdio.h> int main(){ int i=0,j=0; int arr[4][3]={{1,2,3},{4,5,6},{7,8,9},{10,11,12}}; for(i=0;i<4;i++){ for(j=0;j<3;j++){ printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]); } } return 0; }
Output
arr[0] [0] = 1
arr[0] [1] = 2
arr[0] [2] = 3
arr[1] [0] = 4
arr[1] [1] = 5
arr[1] [2] = 6
arr[2] [0] = 7
arr[2] [1] = 8
arr[2] [2] = 9
arr[3] [0] = 10
arr[3] [1] = 11
arr[3] [2] = 12