Contenido del Curso
C++ Intermediate | Mobile-Friendly
C++ Intermediate | Mobile-Friendly
Loops thought Multi-Dimensional Arrays
As you may have noticed, assigning each element of the multi-dimensional array is extremely inconvenient. Here we can use loops! In the beginner c++ course, we used for loop to go through one-dimensional array. Let's modify this method and apply it to a 2-dimensional array:
int x[2][3]; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { x[i][j] = rand() % 10; cout << x[i][j] << " "; } } return 0;
Here we used two for
loops, one for
going thought rows, and another for columns. Then we assign to each element a random value from 0 to 10 and print the result.
You should always remember the rule: one loop for each array's dimensions.
¡Gracias por tus comentarios!