Three- Or Multi-Dimensional Arrays
The ‘C++’ program helps in creating an array of multi dimensions. The compiler determines the restrictions on it. The syntax of the declaration of multi-dimensional arrays is as follows:Data Type_Arrayname [S1][S2][S3]...[Si];
Three-dimensional arrays can be initialized as follows.
int mat[3][3][3] = {1,2,3, 4,5,6, 7,8,9, 1,4,7, 2,5,8, 3,6,9, 1,4,4, 2,4,7, 8,8,5}; |
A three-dimensional array can be considered an array of arrays of arrays. The outer array contains three elements. The inner array is two dimensional with regard to size [3][3].
12.14 Write a program to explain the working of three-dimensional array. #include<iostream.h> #include<conio.h> int main() { int array_3d[3][3][3]; int a,b,c; clrscr(); for (a=0;a<3;a++) for (b=0;b<3;b++) for (c=0;c<3;c++) array_3d[a][b][c]=a+b+c; for (a=0;a<3;a++) { cout<<“\n”; for (b=0;b<3;b++) { for (c=0;c<3;c++) cout<<“ ”<<array_3d[a][b][c]; cout<<“\n”; } } return 0; } |
OUTPUT 2 3 4 3 4 5 2 3 4 3 4 5 4 5 6 |
Explanation: The three-dimensional array array_3d is initialized. The first three for loops are used for adding the values of a, b & c. Here, initially, a & b are zero, and ‘c’ varies from 0 to 2. Hence, the addition of a, b & c will be 0 1 2. This will be printed in the first row. The second output row is one in which a = 0, b = 1, and c varies from 0 to 2. Thus, the output of the second row will be 1 2 3. In this way, the values of a, b & c are changed, and a total of 27 iterations are carried out.