Saturday, April 19, 2025

C++ Elements from Multidimensional Array

To list all elements from a multidimensional array in C++ (two rows, three columns) we can use a combination of for loops.

Basically, we will have for loop inside for loop.

External for loop will be dedicated to list lines, and internal for loop will handle columns.

While combining all positions horizontally and vertically we will get all individual elements printed.

Every time when we print an element, tab is added to the right side. In such way spacing is preserved so that elements are not concatenated while printing them.

Run this code and experiment with it: 

#include <iostream>

using namespace std;

int main() {

    int multiArr[2][3] = {{2, 5, 6}, {4, 7, 9}};

    for (int row = 0; row < 2; row = row + 1) {

        for (int col = 0; col < 3; col = col + 1) {
            cout << multiArr[row][col] << "\t" ;
        }
        cout << endl;
    }

    return 0;

}

Result:

2       5       6
4       7       9

Process returned 0 (0x0)   execution time : 0.021 s
Press any key to continue.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...