4-Dimensional Array in C/C++
A 4D array in C++ is a multidimensional array that has four dimensions. It can be thought of as an array of arrays of arrays of arrays. Each dimension can be indexed independently, starting from 0.
Syntax
data_type array_name[size1][size2][size3][size4];
Here, data_type
is the data type of the elements in the array, array_name
is the name of the array, and size1
, size2
, size3
, and size4
are the sizes of the array in the first, second, third, and fourth dimensions.
Example
#include <iostream>
using namespace std;
int main() {
int arr[2][3][4][5];
for(int i=0; i<2; i++) {
for(int j=0; j<3; j++) {
for(int k=0; k<4; k++) {
for(int l=0; l<5; l++) {
arr[i][j][k][l] = i + j + k + l;
}
}
}
}
for(int i=0; i<2; i++) {
for(int j=0; j<3; j++) {
for(int k=0; k<4; k++) {
for(int l=0; l<5; l++) {
cout << arr[i][j][k][l] << " ";
}
cout << endl;
}
cout << endl;
}
cout << endl;
}
return 0;
}
Output
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
6 7 8 9 10
Explanation
In the above example, we have created a 4D array called arr
with dimensions 2x3x4x5. We have filled the array with the sum of the indices of each element in the array. We then printed the values of the array using nested loops.
Use
4D arrays can be used to represent multi-dimensional data, such as 4D images or 4D scientific datasets. They provide a way to store and manipulate large amounts of complex data, which would be difficult to handle using other data structures.
Important Points
- A 4D array is a multidimensional array with four dimensions.
- Each dimension can be indexed independently, starting from 0.
- 4D arrays can be used to represent multi-dimensional data.
Summary
In summary, a 4D array in C++ is a multidimensional array with four dimensions. It can be used to represent multi-dimensional data and provides a way to store and manipulate large amounts of complex data.