Next generation website theme is here (black, neon and white color) - Reduces eye strain and headache problems.
You are here - Home > Programming > C > Basics

Multi-dimensional Arrays


Array with two or more indexes are called as multi-dimensional arrays, and they can be also referred as arrays of arrays stored in consecutive memory location. Simple example is 2x3 matrix in mathematics where there are two rows and 3 columns.


data_type array_name [number of rows] [number of columns];

Eg: int a[2][3];
int b[3][2] = { {1,3} , {0,1} , {5,2} };
char c[3][3][3];

  • First statement declares 2-dimensional array of integer data type with 2 rows and 3 columns specified in sqaure brackets.
  • Second statement declares and intializes 2-dimensional array of integer data type with 3 rows and 2 columns, intialization of array elements is done between curly brackets. First and last curly bracket denotes start and end of array, while next open and close curly brackets denotes the row and elements in it separated by comma. Similary other two rows are intialized and separated by comma.
  • The last statement declares 3-dimensional array of character data type of 3 size each. Best example of 3-dimensional array is cubic.

Source code

  • //Printing the 2x3 matrix
  • #include <stdio.h>
  • void main()
  • {
  • int A[2][3] ={ {1,2,4},{2,4,1}};
  • int i,j;
  • printf("Matrix A is\n");
  • for(i=0;i<2;i++)
  • {
  • for(j=0;j<3;j++)
  • {
  • printf("%d\t",a[i][j]);
  • }
  • printf("\n");
  • }
  • }

Program working steps

  • First line is the comment of the program 2nd line is header file statment, which includes definition of printf function.
  • 4th line main function which returns nothing and this is where program execution starts.
  • Declration and initialization of 2-dimensional array A of integer data type with 2 rows and 3 columns. Left side of statement declares the dimnension and size of array in square brackerts while right part of statement initializes the elements in the array within curly brackets ending with a semicolon.
  • Declration of variable int i and j to use in for loop and next is the simple printf statement.
  • First for loop for rows with condition i<2 and second for columns with condition j<3. In second for loop block code, it prints the first row of the martix A as row value i remains constant and column value j goes on increasing. Escape sequence \t is used to differentiate the elements.
  • After ending the 2nd for loop printf statement with esapce sequence \n is used to print the next row on new line.
  • First for loop ends when two rows are printed and this exits the program.

Tip Box

Remeber : Program doesn't stores the multi-dimensional array in the form of tables or grid, it stores the array in continious memory location such as chain.


Terms of Use | Privacy Policy | Contact Us | Advertise
CodesandTutorials © 2014 All Rights Reserved