print 2d array
Here is an example of how to print a 2D array in C++, along with explanations for each step:
#include <iostream>
int main() {
int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
Step 1: Include the <iostream>
header file, which is required for input/output operations in C++.
Step 2: Define the main()
function, which serves as the entry point for the program.
Step 3: Declare a 2D array called arr
with dimensions 3x3. In this example, we initialize the array with some values for demonstration purposes.
Step 4: Use nested for loops to iterate over each element in the 2D array. The outer loop iterates over the rows, and the inner loop iterates over the columns.
Step 5: Inside the inner loop, use std::cout
to print the value of each element in the 2D array. In this example, we separate the elements with a space for readability.
Step 6: After printing all the elements in a row, use std::endl
to move to the next line and start a new row.
Step 7: Finally, return 0 from the main()
function to indicate successful execution of the program.
This code will output the 2D array in a grid-like format, with each element separated by a space and each row on a new line. The output for the given example will be:
1 2 3
4 5 6
7 8 9
Let me know if you have any further questions.