c++ 2 dim array initialize

#include <iostream>
using namespace std;

const int ROWS = 3;
const int COLS = 4;

int main() {
    int array_2D[ROWS][COLS] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12}
    };

    // Accessing and printing the elements of the 2D array
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            cout << array_2D[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

Explanation:

  • #include <iostream>: Includes the input/output stream library to enable input and output operations.
  • using namespace std;: Allows the usage of standard library functions without explicitly specifying the namespace.
  • const int ROWS = 3; and const int COLS = 4;: Declares constants representing the number of rows and columns in the 2D array.
  • int main() { ... }: Entry point of the program.
  • int array_2D[ROWS][COLS]: Declares a 2D array named array_2D with 3 rows and 4 columns.
  • = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }: Initializes the elements of the 2D array with values in row-major order.
  • Nested loops (for loops):
  • for (int i = 0; i < ROWS; ++i) { ... }: Outer loop iterates through each row of the 2D array.
  • for (int j = 0; j < COLS; ++j) { ... }: Inner loop iterates through each column of the current row.
  • cout << array_2D[i][j] << " ";: Prints each element of the 2D array separated by a space.
  • cout << endl;: Moves to the next line after printing all elements of a row.

This program initializes a 2D array, prints its contents, and uses nested loops to access and display each element in a row-column format.