C Multi Dimensional Array Module
C Multi Dimensional Array Module
C Multi Dimensional Array Module
int x[3][4];
Elements in two-dimensional
array in C++ Programming
Three-dimensional arrays also work in a similar way. For example:
float x[2][4][3];
The above method is not preferred. A better way to initialize this array with the
same array elements is given below:
This array has 2 rows and 3 columns, which is why we have two rows of
elements with 3 elements each.
Initializing a two-dimensional
array in C++
2. Initialization of three-dimensional array
int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
};
The first dimension has the value 2 . So, the two elements comprising the first
dimension are:
The second dimension has the value 3 . Notice that each of the elements of
the first dimension has three elements each:
{3, 4, 2, 3}, {0, -3, 9, 11} and {23, 12, 23, 2} for Element 1.
Finally, there are four int numbers inside each of the elements of the second
dimension:
{3, 4, 2, 3}
{0, -3, 9, 11}
... .. ...
... .. ...
#include <iostream>
using namespace std;
int main() {
int test[3][2] = {{2, -5},
{4, 0},
{9, 1}};
return 0;
}
Output
test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1
int main() {
int numbers[2][3];
Output
Enter 6 numbers:
1
2
3
4
5
6
The numbers are:
numbers[0][0]: 1
numbers[0][1]: 2
numbers[0][2]: 3
numbers[1][0]: 4
numbers[1][1]: 5
numbers[1][2]: 6
Here, we have used a nested for loop to take the input of the 2d array. Once
all the input has been taken, we have used another nested for loop to print
the array members.
#include <iostream>
using namespace std;
int main() {
// This array can store upto 12 elements (2x3x2)
int test[2][3][2] = {
{
{1, 2},
{3, 4},
{5, 6}
},
{
{7, 8},
{9, 10},
{11, 12}
}
};
return 0;
}
Output
test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12
• the outer loop from i == 0 to i == 1 accesses the first dimension of the array
• the middle loop from j == 0 to j == 2 accesses the second dimension of the
array
• the innermost loop from k == 0 to k == 1 accesses the third dimension of the
array
As we can see, the complexity of the array increases exponentially with the
increase in dimensions.