loop over multidimensional array c++
To loop over a multidimensional array in C++, you can use nested loops. Here is an example of how to do it:
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++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
Explanation:
1. Declare and initialize a 2D array named arr
with dimensions 3x3. This array holds integer values.
2. The outer loop, for (int i = 0; i < 3; i++)
, iterates over the rows of the array. In this case, i
represents the row index.
3. The inner loop, for (int j = 0; j < 3; j++)
, iterates over the columns of each row. j
represents the column index.
4. Inside the inner loop, cout << arr[i][j] << " ";
prints the value of the element at the current row and column position.
5. After printing all the elements of a row, cout << endl;
is used to move to the next line, creating a matrix-like format.
6. The loops continue until all the elements of the 2D array have been printed.
This code will output the following:
1 2 3
4 5 6
7 8 9
This is a simple example of how to loop over a 2D array in C++. Let me know if you have any further questions!