Initialization of Multidimensional Arrays in C++
Last Updated :
12 Feb, 2024
In C++, multidimensional arrays are the type of arrays that have multiple dimensions, i.e., they can expand in multiple directions. In this article, we will discuss how to initialize the multidimensional arrays in C++.
Methods to Initialize Multidimensional Array in C++
We can initialize multidimensional arrays in C++ using the following ways:
- Initialization using Initializer List
- Initialization with Default Values
1. Initialization Using Initializer List
We can initialize the multidimensional arrays using the list initialization as shown:
Initializing 2D Arrays
arr[2][3] = { {1, 2, 3}, {4, 5, 6} };
Initializing 3D Arrays
arr[2][3][2] = { { {1, 2}, {3, 4}, {5, 6} }, { {7, 8}, {9, 10}, {11, 12} } };
Example
C++
#include <iostream>
using namespace std;
int main()
{
int arr[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
int arr1[2][3][2] = { { { 1, 2 }, { 3, 4 }, { 5, 6 } },
{ { 7, 8 }, { 9, 10 }, { 11, 12 } } };
cout << "2D Array: " ;
for ( int i = 0; i < 2; i++) {
for ( int j = 0; j < 3; j++) {
cout << arr[i][j] << " " ;
}
}
cout << endl;
cout << "3D Array: " ;
for ( int i = 0; i < 2; i++) {
for ( int j = 0; j < 3; j++) {
for ( int k = 0; k < 2; k++) {
cout << arr1[i][j][k] << " " ;
}
}
}
return 0;
}
|
Output
2D Array: 1 2 3 4 5 6
3D Array: 1 2 3 4 5 6 7 8 9 10 11 12
2. Initialization with Zero
In C++, we can initialize the multidimensional array with a zero in a single statement.
Syntax
arr[2][3] = {0}
Here, all the elements will be initialized with the value zero.
Example
C++
#include <iostream>
using namespace std;
int main()
{
int array[2][3] = { 0 };
for ( int i = 0; i < 2; ++i) {
for ( int j = 0; j < 3; ++j) {
cout << array[i][j] << " " ;
}
cout << endl;
}
return 0;
}
|
Conclusion
In summary, initializing multidimensional arrays in C++ involves setting them up with initial values(Providing the values in code itself). There are few different method of initialization discussed in this article. We can choose the relevant method according to our choice.
Share your thoughts in the comments
Please Login to comment...