C - Multi Dimensional Arrays

C Programming

Share

In this tutorial we will learn about multi dimensional array in C programming language.

We have already covered one dimensional arrays and two dimensional arrays in the previous tutorials.

In C we can create multi dimensional arrays just like 1D and 2D arrays. The syntax for a multi dimensional array is given below.

type arrName[size1][size2]...[sizeN];

In the above syntax type is any valid type like int, float etc. arrName is the name of the array and [size1], [size2], ... are the dimensions of the array.

Array dimension limit is determined by the compiler being used to compile the C program.

Arrays over 2D gets complicated!

3D arrays

In the following example we will create a 3D array named scoreboard of type int to hold score of 3 matches of 2 players for 2 consecutive years.

//scoreboard[player][match][year]
int scoreboard[2][3][2];

The array will look like the following.



Lets write a program in C to take score of 2 players for the 3 matches for 2 years.

/**
 * file: 3d-array.c
 * author: yusuf shakeel
 * date: 2010-12-25
 * description: 3d array program
 */

#include <stdio.h>
int main(void)
{
  //variable
  int
    scoreboard[2][3][2],
    player, match, year;
    
  //user input
  printf("---------- INPUT ----------\n\n");
  for (year = 0; year < 2; year++) {
    printf("---------- Year #%d ----------\n", (year + 1));
    for (player = 0; player < 2; player++) {
      printf("Enter score of Player #%d\n", (player + 1));
      for (match = 0; match < 3; match++) {
        printf("Match #%d: ", (match + 1));
        scanf("%d", &scoreboard[player][match][year]);
      }
    }
  }
  
  //output
  printf("\n\n---------- OUTPUT ----------\n\n");
  for (year = 0; year < 2; year++) {
    printf("---------- Scoreboard of Year #%d ----------\n", (year + 1));
    for (player = 0; player < 2; player++) {
      printf("----- Player #%d -----\n", (player + 1));
      for (match = 0; match < 3; match++) {
        printf("Match #%d: %d\n", (match + 1), scoreboard[player][match][year]);
      }
    }
  }
  
  printf("End of code\n");
  return 0;
}

Output

---------- INPUT ----------

---------- Year #1 ----------
Enter score of Player #1
Match #1: 80
Match #2: 40
Match #3: 70
Enter score of Player #2
Match #1: 50
Match #2: 90
Match #3: 30
---------- Year #2 ----------
Enter score of Player #1
Match #1: 80
Match #2: 90
Match #3: 70
Enter score of Player #2
Match #1: 40
Match #2: 60
Match #3: 70


---------- OUTPUT ----------


---------- Scoreboard of Year #1 ----------
----- Player #1 -----
Match #1: 80
Match #2: 40
Match #3: 70
----- Player #2 -----
Match #1: 50
Match #2: 90
Match #3: 30
---------- Scoreboard of Year #2 ----------
----- Player #1 -----
Match #1: 80
Match #2: 90
Match #3: 70
----- Player #2 -----
Match #1: 40
Match #2: 60
Match #3: 70
End of code
Share