codescracker
c

C Program for Three Dimensional Array



« Previous Program Next Program »

In this article, you will learn and get code on three dimensional array in C programming.

How to Find Size of Three Dimensional Array

To find the size of three dimensional array say arr[i][j][k]. The formula is:

size = i*j*k

For example, if a given array is arr[3][4][2]. Then its size will be:

size = 3*4*2
     = 24

That is, it can hold upto 24 elements.

Three Dimensional Array Program in C

An array of three dimension say arr[3][4][2] indicates, 3 two-dimensional array of size 4*2. That is, the two dimensional array has 4 rows and 2 columns. Its initialization goes like:

arr[3][4][2] = { 
              { {1, 2}, {3, 4}, {5, 6}, {7, 8} },
              { {8, 7}, {6, 5}, {4, 3}, {2, 1} },
              { {1, 3}, {5, 7}, {9, 7}, {5, 3} }
            };

As you can see, there are three two dimensional array with 4 rows and 2 columns each. Now let's move on to the program.

Three dimensional (3D) array uses three for loops in programming. Therefore, if you want to initialize dynamically or to print its elements on output, you have to use three for loops. Like the program given below uses the same to print all the elements of three-dimensional array on output:

#include<stdio.h>
#include<conio.h>
int main()
{
   int i, j, k;
   int arr[3][4][2] = {
      { {2, 4}, {7, 8}, {3, 4}, {5, 6} },
      { {7, 6}, {3, 4}, {5, 3}, {2, 3} },
      { {8, 9}, {7, 2}, {3, 4}, {5, 1} }
      };
   for(i=0; i<3; i++)
   {
      for(j=0; j<4; j++)
      {
         for(k=0; k<2; k++)
            printf("%d  ", arr[i][j][k]);
         printf("\n");
      }
      printf("\n");
   }
   getch();
   return 0;
}

This program was build and run under Code::Blocks IDE. Here is its sample output:

three dimensional array programming in c

As you can see from the output given above, there are three two dimensional array gets printed.

Print 3D Array Elements along with its Index

To print all elements along with its index numbers. Here is the program:

#include<stdio.h>
#include<conio.h>
int main()
{
   int i, j, k;
   int arr[3][4][2] = {
      { {2, 4}, {7, 8}, {3, 4}, {5, 6} },
      { {7, 6}, {3, 4}, {5, 3}, {2, 3} },
      { {8, 9}, {7, 2}, {3, 4}, {5, 1} }
      };
   for(i=0; i<3; i++)
   {
      for(j=0; j<4; j++)
      {
         for(k=0; k<2; k++)
            printf("arr[%d][%d][%d] = %d  ", i, j, k, arr[i][j][k]);
         printf("\n");
      }
      printf("\n");
   }
   getch();
   return 0;
}

Here is its sample output:

c three dimensional array program

Same Program in Other Languages

C Online Test


« Previous Program Next Program »



© Copyright 2021. All Rights Reserved.

CodesCracker