Node:Arrays and nested loops, Next:, Previous:Multidimensional arrays, Up:Arrays

Arrays and nested loops

To initialize multidimensional arrays, you can use nested for loops. Three nested loops are needed to initialize a three-dimensional array:

#include <stdio.h>

#define SIZE1 3
#define SIZE2 3
#define SIZE3 3

int main ()
  int fast, faster, fastest;
  int my_array[SIZE1][SIZE2][SIZE3];

  for (fast = 0; fast < SIZE1; fast++)
      for (faster = 0; faster < SIZE2; faster++)
	  for (fastest = 0; fastest < SIZE3; fastest++)
	      my_array[fast][faster][fastest] = 0;
	      printf("my_array[%d][%d][%d] DONE\n", fast, faster, fastest);

In this example, the variables fast, faster, and fastest contain the indices of the array, and vary fast, faster, and fastest, respectively. In the example output below, you can see that the fastest index changes every line, while the faster index changes every three lines, and the fast index changes only every nine lines.

my_array[0][0][0] DONE
my_array[0][0][1] DONE
my_array[0][0][2] DONE
my_array[0][1][0] DONE
my_array[0][1][1] DONE
my_array[0][1][2] DONE
my_array[0][2][0] DONE
my_array[0][2][1] DONE
my_array[0][2][2] DONE
my_array[1][0][0] DONE
my_array[1][0][1] DONE
my_array[1][0][2] DONE
my_array[1][1][0] DONE
my_array[1][1][1] DONE
my_array[1][1][2] DONE
my_array[1][2][0] DONE
my_array[1][2][1] DONE
my_array[1][2][2] DONE
my_array[2][0][0] DONE
my_array[2][0][1] DONE
my_array[2][0][2] DONE
my_array[2][1][0] DONE
my_array[2][1][1] DONE
my_array[2][1][2] DONE
my_array[2][2][0] DONE
my_array[2][2][1] DONE
my_array[2][2][2] DONE

Note: Although in this example we have followed the order in which indices vary inside the computer, you do not have to do so in your own code. For example, we could have switched the nesting of the innermost fastest and outermost fast loops, and every element would still have been initialized. It is better, however, to be systematic about initializing multidimensional arrays.