C++ Code Example 1: multidimensional array

This program declares and initializes a 2D array myArray with dimensions 2×4. The first loop with the variable i iterates over the rows of the array and the second loop with the variable j iterates over the columns.

The elements of the array are assigned values 1 to 8 in row-major order, meaning all elements of a row are assigned values before moving on to the next row.

Finally, the elements of the array are printed row by row to the console.

#include <iostream>
using namespace std;

int main() {
    int myArray[2][4];

    myArray[0][0] = 1;
    myArray[0][1] = 2;
    myArray[0][2] = 3;
    myArray[0][3] = 4;
    myArray[1][0] = 5;
    myArray[1][1] = 6;
    myArray[1][2] = 7;
    myArray[1][3] = 8;

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 4; j++) {
            cout << myArray[i][j];
        }
        cout << endl;
    }

    return 0;
}
Output
1234
5678