Saturday, June 18, 2022
HomeWordPress DevelopmentThe right way to iterate a Multidimensional Array?

The right way to iterate a Multidimensional Array?


View Dialogue

Enhance Article

Save Article

Like Article

Multidimensional arrays are arrays which have multiple dimension. For instance, a easy array is a 1-D array, a matrix is a 2-D array, and a dice or cuboid is a 3-D array however find out how to visualize arrays with greater than 3 dimensions, and find out how to iterate over parts of those arrays? It’s easy, simply consider any multidimensional array as a set of arrays of decrease dimensions.

n-D array = Assortment of (n-1)D arrays 

For instance, a matrix or 2-D array is a set of 1-D arrays.

2D Array is a collection of 1D Arrays

2D Array is a set of 1D Arrays

Equally, you may visualize 3-D arrays and different multidimensional arrays.

The right way to iterate over parts of a Multidimensional array? 

It may be noticed that solely a 1-D array comprises parts and a multidimensional array comprises smaller dimension arrays.

  •  Therefore first iterate over the smaller dimension array and iterate over the 1-D array inside it. 
  • Doing this for the entire multidimensional array will iterate over all parts of the multidimensional array.

Instance 1: Iterating over a 2-D array

C++

#embody <bits/stdc++.h>

utilizing namespace std;

  

int predominant()

{

    

    int n = 3;

    int m = 3;

    int arr[][3]

        = { { 3, 2, 7 }, { 2, 6, 8 }, { 5, 1, 9 } };

  

    

    for (int i = 0; i < n; i++) {

  

        

        for (int j = 0; j < m; j++) {

  

            

            cout << arr[i][j] << " ";

        }

        cout << endl;

    }

    return 0;

}

Instance 2: Iterating over a 3D array

C++

#embody <bits/stdc++.h>

utilizing namespace std;

  

int predominant()

{

    

    int x = 2, y = 2, z = 2;

    int arr[][3][2] = { { { 1, 2 }, { 3, 4 } },

                        { { 5, 6 }, { 7, 8 } } };

  

    

    for (int i = 0; i < x; i++) {

        cout << "Inside " << i + 1

             << " 2D array in 3-D array" << endl;

  

        

        for (int j = 0; j < y; j++) {

            cout << "Inside " << j + 1

                 << " 1D array of the 2-D array" << endl;

  

            

            for (int okay = 0; okay < z; okay++) {

                cout << arr[i][j][k] << " ";

            }

            cout << endl;

        }

        cout << endl;

    }

    return 0;

}

Output

Inside 1 2D array in 3-D array
Inside 1 1D array of the 2-D array
1 2 
Inside 2 1D array of the 2-D array
3 4 

Inside 2 2D array in 3-D array
Inside 1 1D array of the 2-D array
5 6 
Inside 2 1D array of the 2-D array
7 8 


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments