Printing a 2D array in C++ is similar to printing a 1D array, but instead of a single loop, you use nested loops to iterate over the rows and columns of the 2D array.
Here’s an example program that demonstrates how to print a 2D array:
#include <iostream>
int main() {
// Define the 2D array
int arr[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Define the dimensions of the array
int rows = 3;
int cols = 3;
// Print the 2D array
std::cout << “2D array:” << std::endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// Print the element at [i][j]
std::cout << arr[i][j] << ” “;
}
// Print a new line after each row
std::cout << std::endl;
}
return 0;
}
Here’s how the program works:
- The program starts by defining a 2D array (arr) with 3 rows and 3 columns, and some example values.
- The rows and cols variables are used to specify the number of rows and columns in the array.
- A nested loop is used to iterate over the 2D array.
- The outer loop iterates over each row of the array.
- The inner loop iterates over each column of the current row.
- Each element at position [i][j] in the array is printed, followed by a space.
- After printing all the elements in a row, a new line is printed to separate rows visually.
- This continues until all rows are printed, resulting in the 2D array being displayed in a matrix-like format.