Multi-Dimensional Array in C Programming Language

Rumman Ansari   Software Engineer   2019-03-31   26755 Share
☰ Table of Contents

Table of Content:


So far we have explored arrays with only one dimension. It is also possible for arrays to have two or more dimensions. C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.

The two dimensional array is also called a matrix.

In C programming, you can create an array of arrays known as a multi-dimensional array. For example,

float x[3][4]; 

Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as a table with 3 row and each row has 4 column.

Two Dimensional Array in c programming language

Similarly, you can declare a three-dimensional (3d) array. For example,

float y[2][4][3];

Here, The array y can hold 24 elements.

You can think this example as: Each 2 elements have 4 elements, which makes 8 elements and each 8 elements can have 3 elements. Hence, the total number of elements is 24.

How to initialize a multidimensional array?

There is more than one way to initialize a multidimensional array.

Initialization of a two dimensional array

// Different ways to initialize two dimensional array

int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
         
int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
                
int c[2][3] = {1, 3, 0, -1, 5, 9};

Above code are three different ways to initialize two-dimensional arrays.

Initialization of a three-dimensional array.

You can initialize a three-dimensional array in a similar way like a two-dimensional array. Here's an example,

int test[2][3][4] = { 
                     { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
                     { {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} }
                 };

Example 1: Two-Dimensional Array to store and display values

 // C program to store temperature of two cities for a week and display it.
#include 

const int CITY = 2;
const int WEEK = 7;

int main()
{
	int i, j;
    int temperature[CITY][WEEK];
    for (i = 0; i < CITY; ++i) {
        for(j = 0; j < WEEK; ++j) {
            printf("City %d, Day %d: ", i+1, j+1);
            scanf("%d", &temperature[i][j]);
        }
    }

    printf("\nDisplaying values: \n\n");
    for (i = 0; i < CITY; ++i) {
        for(j = 0; j < WEEK; ++j)
        {
            printf("City %d, Day %d = %d\n", i+1, j+1, temperature[i][j]);
        }
    }
    return 0;
}
 
 City 1, Day 1: 25
City 1, Day 2: 24
City 1, Day 3: 26
City 1, Day 4: 16
City 1, Day 5: 13
City 1, Day 6: 12
City 1, Day 7: 14
City 2, Day 1: 18
City 2, Day 2: 19
City 2, Day 3: 14
City 2, Day 4: 25
City 2, Day 5: 31
City 2, Day 6: 30
City 2, Day 7: 17

Displaying values:

City 1, Day 1 = 25
City 1, Day 2 = 24
City 1, Day 3 = 26
City 1, Day 4 = 16
City 1, Day 5 = 13
City 1, Day 6 = 12
City 1, Day 7 = 14
City 2, Day 1 = 18
City 2, Day 2 = 19
City 2, Day 3 = 14
City 2, Day 4 = 25
City 2, Day 5 = 31
City 2, Day 6 = 30
City 2, Day 7 = 17
Press any key to continue . . .
 

Example 2: Sum of two matrices using Two-dimensional arrays

C program to find the sum of two matrices of order 2*2 using multidimensional arrays.

#include
int main()
{
   float a[2][2], b[2][2], c[2][2];
   int i, j;

   // Taking input using nested for loop
   printf("Enter elements of 1st matrix\n");
   for(i=0; i<2; ++i)
    for(j=0; j<2; ++j)
    {
       printf("Enter a%d%d: ", i+1, j+1);
       scanf("%f", &a[i][j]);
    }

  // Taking input using nested for loop
   printf("Enter elements of 2nd matrix\n");
   for(i=0; i<2; ++i)
    for(j=0; j<2; ++j)
    {
       printf("Enter b%d%d: ", i+1, j+1);
       scanf("%f", &b[i][j]);
    }

   // adding corresponding elements of two arrays
   for(i=0; i<2; ++i)
    for(j=0; j<2; ++j)
    {
       c[i][j] = a[i][j] + b[i][j]; 
    }

   // Displaying the sum
   printf("\nSum Of Matrix: \n");

   for(i=0; i<2; ++i)
    for(j=0; j<2; ++j)
    {
       printf("%.1f\t", c[i][j]);  
       
       if(j==1)            
          printf("\n");
    }
return 0;
}
Enter elements of 1st matrix
Enter a11: 1
Enter a12: 2
Enter a21: 3
Enter a22: 3
Enter elements of 2nd matrix
Enter b11: 2
Enter b12: 1
Enter b21: 4
Enter b22: 2

Sum Of Matrix:
3.0     3.0
7.0     5.0
Press any key to continue . . .

Multi-Dimension Arrays

Array Declaration

A multidimensional array is declared using the following syntax:

type array_name[d1][d2][d3][d4]………[dn];

Example

int table[5][5][20]; 
  • int designates the array type integer.

  • table is the name of our 3D array.

  • Our array can hold 500 integer-type elements. This number is reached by multiplying the value of each dimension. In this case: 5x5x20=500.

 
float arr[5][6][5][6][5];
  • Array arr is a five-dimensional array.

  • It can hold 4500 floating-point elements (5x6x5x6x5=4500).

Can you see the power of declaring an array over variables? When it comes to holding multiple values in C programming, we would need to declare several variables. But a single array can hold thousands of values.

Note: For the sake of simplicity, this tutorial discusses 3D arrays only. Once you grab the logic of how the 3D array works then you can handle 4D arrays and larger.

Explanation of a 3D Array

Let's take a closer look at a 3D array. A 3D array is essentially an array of arrays of arrays: it's an array or collection of 2D arrays, and a 2D array is an array of 1D array.

It may sound a bit confusing, but don't worry. As you practice working with multidimensional arrays, you start to grasp the logic.

The diagram below may help you understand:

Three Dimensional Array in c programming language

Address and view

Three Dimensional Array in c programming language

Initializing a 3D Array in C

Like any other variable or array, a 3D array can be initialized at the time of compilation. By default, in C, an uninitialized 3D array contains “garbage” values, not valid for the intended use.

Let’s see a complete example on how to initialize a 3D array:

Syntax:

#include
#include
 
void main()
{
int i, j, k;
int arr[3][3][3]=   
        {
            {
            {11, 12, 13},
            {14, 15, 16},
            {17, 18, 19}
            },
            {
            {21, 22, 23},
            {24, 25, 26},
            {27, 28, 29}
            },
            {
            {31, 32, 33},
            {34, 35, 36},
            {37, 38, 39}
            },
        };
 
printf(":::3D Array Elements:::\n\n");
for(i=0;i<3;i++)
{
    for(j=0;j<3;j++)
    {
        for(k=0;k<3;k++)
        {
        printf("%d\t",arr[i][j][k]);
        }
        printf("\n");
    }
    printf("\n");
}
getch();
}
:::3D Array Elements:::

11      12      13
14      15      16
17      18      19

21      22      23
24      25      26
27      28      29

31      32      33
34      35      36
37      38      39


In the code above we have declared a multidimensional integer array named “arr” which can hold 3x3x3 (or 27) elements.

We have also initialized the multidimensional array with some integer values.

As I said earlier, a 3D array is an array of 2D arrays. I have divided elements accordingly for easy understanding. Looking at the C code sample above,

  • In lines 9-13, 14-18, and 19-23, each block is a 2D array.
  • Collectively, lines 2-24 make a 3D array.

To call values from the array, imagine the 3D array above as a collection of tables. Each nested bracket cluster is a table with rows and columns. To access or store any element in a 3D array you need to know its table number, row number, and column number.

An example: You need to access value 25 from the above 3D array. So, first check the table: in this case, 25 is in table 1 (remember: tables, rows, columns are counted starting at 0, so the second table is table 1). Once you find the table number now check which row of that table has the value and then check the column number. So applying above logic, 25 located in table 1, row 1, and column 1, hence the address is arr[1][1][1]. Print this address and you will get the output: 25.

The Conceptual Syntax of a 3D Array in C

The conceptual syntax for 3D array is this:

data_type array_name[table][row][column];

If you want to store values in any 3D array point first to table number, then row number, and lastly to column number.

Some hypothetical examples:

arr[0][1][2] = 32;
arr[1][0][1] = 49;

Storing Values in a Continuous Location Using a Loop

The pointer syntax above assigns values to a particular location of an array, but if you want to store values in multiple locations automataically then you should use a loop.

Here is an example using the for loop command:

#include
#include
 
void main()
{
int i, j, k, x=1;
int arr[3][3][3]; 
printf(":::3D Array Elements:::\n\n");
 
for(i=0;i<3;i++)
{
    for(j=0;j<3;j++)
    {
        for(k=0;k<3;k++)
        {
        arr[i][j][k] = x;
        printf("%d\t",arr[i][j][k]);
        x++;
        }
        printf("\n");
    }
    printf("\n");
}
getch();
}
:::3D Array Elements:::

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      27


Another Example of Three Dimensional Array

 #include 
int main()
{
    // this array can store 12 elements

    int i, j, k, test[2][3][2];

    printf("Enter 12 values: \n");

    for(i = 0; i < 2; ++i) {
        for (j = 0; j < 3; ++j) {
            for(k = 0; k < 2; ++k ) {
                scanf("%d", &test[i][j][k]);
            }
        }
    }

    // Displaying values with proper index.

    printf("\nDisplaying values:\n");

    for(i = 0; i < 2; ++i) {
        for (j = 0; j < 3; ++j) {
            for(k = 0; k < 2; ++k ) {
                printf("test[%d][%d][%d] = %d\n", i, j, k, test[i][j][k]);
            }
        }
    }

    return 0;
}
 
 Enter 12 values:
1
3
6
4
2
6
9
1
8
4
1
9

Displaying values:
test[0][0][0] = 1
test[0][0][1] = 3
test[0][1][0] = 6
test[0][1][1] = 4
test[0][2][0] = 2
test[0][2][1] = 6
test[1][0][0] = 9
test[1][0][1] = 1
test[1][1][0] = 8
test[1][1][1] = 4
test[1][2][0] = 1
test[1][2][1] = 9
Press any key to continue . . .