Three Dimensional Array Example in C++


This is a C++ program that creates a 3D array and prints out its elements. Here's how the program works:

  • The program creates a 3D array called arr with dimensions 2 x 3 x 2. This means the array has two "layers", each with three rows and two columns.
  • The program initializes the array with some values.
  • The program uses three nested loops to iterate over all the elements of the array.
  • The outer loop iterates over the two "layers" of the array, using the variable x as the index.
  • The middle loop iterates over the three rows in each layer, using the variable y as the index.
  • The inner loop iterates over the two columns in each row, using the variable z as the index.
  • The program prints out each element of the array, separated by a space.
  • After printing all the elements in a row, the program prints a newline character to start a new row.
  • After printing all the rows in a layer, the program prints an extra newline character to separate the layers.
  • After printing all the layers, the program ends.

Overall, this program creates and prints a 3D array in a nested loop structure. It is useful for understanding how multi-dimensional arrays work and how to iterate over their elements using nested loops.

Source Code

#include <iostream>
using namespace std;
int main()
{
  int arr[2][3][2] = {
      { {1,-1},{2,-2}, {3,-3} },
      { {4,-4},{5,-5}, {6,-6} }
  };
  for (int x=0;x<2;x++)
  {
    for (int y=0;y<3;y++)
    {
       for (int z=0;z<2;z++)
       {
        cout<<arr[x][y][z]<<" ";
       }
       cout<<"\n";
    }
    cout<<"\n";
  }
  return 0;
}
To download raw file Click Here

Output

1 -1 
2 -2 
3 -3 

4 -4 
5 -5 
6 -6 

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples