What is Multidimensional Arrays - C Array

C examples for Array:Multidimensional Arrays

Introduction

A two-dimensional array can be declared as follows:

float myarray[25][50];

This declares the myarray array with 25 sets of 50 floating-point elements.

Similarly, you could declare another two-dimensional array of floating-point numbers with this statement:

float numbers[3][5];

Initializing Multidimensional Arrays

To initialize a two-dimensional array, put the initial values for each row between braces, {}, and then enclose all the rows between braces.

int numbers[3][4] = {
                      { 10, 20, 30, 40 },          // Values for first row
                      { 15, 25, 35, 45 },          // Values for second row
                      { 47, 48, 49, 50 }           // Values for third row
                    };

You can initialize the whole array to 0 by supplying just one value:

int numbers[3][4] = {0};

A three-dimensional array will have three levels of nested braces, with the inner level containing sets of initializing values for a row:

int numbers[2][3][4] = {
                           {                       // First block of 3 rows
                             { 10, 20, 30, 40 },
                             { 15, 25, 35, 45 },
                             { 47, 48, 49, 50 }
                           },
                           {                       // Second block of 3 rows
                             { 10, 20, 30, 40 },
                             { 15, 25, 35, 45 },
                             { 47, 48, 49, 50 }
                          }
                       };

You need a nested loop to process all the elements in a multidimensional array.

Here's how you could sum the elements in the previous numbers array:

Demo Code

#include <stdio.h> 
int main(void) { 

    int numbers[2][3][4] = {
                           {                       // First block of 3 rows
                             { 10, 20, 30, 40 },
                             { 15, 25, 35, 45 },
                             { 47, 48, 49, 50 }
                           },/* w  w w .  j  ava 2 s.  c  o m*/
                           {                       // Second block of 3 rows
                             { 10, 20, 30, 40 },
                             { 15, 25, 35, 45 },
                             { 47, 48, 49, 50 }
                          }
                       };
    int sum = 0;
    for(int i = 0 ; i < 2 ; ++i)
    {
      for(int j = 0 ; j < 3 ; ++j)
      {
        for(int k = 0 ; k < 4 ; ++k)
        {
          sum += numbers[i][j][k];
        }
      }
    }
    printf("The sum of the values in the numbers array is %d.", sum);
    return 0; 
}

Result


Related Tutorials