What is the method for traversing a two-dimensional array in C++?
In C++, you can use two nested for loops to iterate through a two-dimensional array. Initially, use the outer loop to iterate through each row, and then within the inner loop, traverse through each column.
Here is an example code showing how to iterate through a two-dimensional array using two for loops.
#include <iostream>
int main() {
int arr[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
// 遍历二维数组
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
The output is:
1 2 3 4
5 6 7 8
9 10 11 12
In the example above, the outer loop variable i is used to iterate through each row, while the inner loop variable j is used to traverse each column in the current row. Elements in the array are accessed using arr[i][j].