Open In App

Initialization of Multidimensional Arrays in C++

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:



  1. Initialization using Initializer List
  2. 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++ program to illustrate how to initialize the
// multidimensional array
#include <iostream>
using namespace std;
  
int main()
{
    // Declaring a 2D array with 2 rows and 3 columns
    int arr[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
  
    // Declaring a 3D array with 2 rows and 3 columns and 2
    // depth
    int arr1[2][3][2] = { { { 1, 2 }, { 3, 4 }, { 5, 6 } },
                     { { 7, 8 }, { 9, 10 }, { 11, 12 } } };
  
    // printing 2d array
    cout << "2D Array: ";
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            cout << arr[i][j] << " ";
        }
    }
    cout << endl;
  
    // printing 2d array
    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++ program to initialize 2D array with zero
#include <iostream>
using namespace std;
  
int main()
{
    // Declare and initialize a 2D array with 2 rows and 3
    // columns
    int array[2][3] = { 0 };
  
    // Output the values
    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 3; ++j) {
            // Output each element of the array
            cout << array[i][j] << " ";
        }
        // Move to the next line after printing each row
        cout << endl;
    }
  
    return 0;
}

Output
0 0 0 
0 0 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.


Article Tags :