Lesson Proper For Week 8: C++ Multidimensional Arrays
Lesson Proper For Week 8: C++ Multidimensional Arrays
In this tutorial, we'll learn about multi-dimensional arrays in C++. More specifically, how to declare
them, access them, and use them efficiently in our program.
In C++, we can create an array of an array, known as a multidimensional array. For example:
int x[3][4];
We can think of this array as a table with 3 rows and each row has 4 columns as shown below.
float x[2][4][3];
We can find out the total number of elements in the array simply by multiplying its dimensions:
2 x 4 x 3 = 24
Like a normal array, we can initialize a multidimensional array in more than one way.
This array has 2 rows and 3 columns, which is why we have two rows of elements with 3 elements
each.
This is not a good way of initializing a three-dimensional array. A better way to initialise this array is:
int test[2][3][4] = {
};
#include <iostream>
int main() {
cout << "test[" << i << "][" << j << "] = " << test[i][j] << endl;
}
}
return 0;
Run Code
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
· the outer loop from i = 0 to i = 2 access the rows of the array
· the inner loop from j = 0 to j = 1 access the columns of the array
#include <iostream>
int main() {
}
}
cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] << endl;
}
}
return 0;
Run Code
Output
Enter 6 numbers:
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>
int main() {
{
{1, 2},
{5, 6}
},
{
}
};
cout << "test[" << i << "][" << j << "][" << k << "] = " << test[i][j][k] << endl;
}
}
}
return 0;
Run Code
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
However, since we are manipulating 3 dimensions, we use a nested for loop with 3 total loops
instead of just 2.
As we can see, the complexity of the array increases exponentially with the increase in dimensions.