Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Loops thought Multi-Dimensional Arrays | Data Types and Arrays
C++ Intermediate | Mobile-Friendly
course content

Contenido del Curso

C++ Intermediate | Mobile-Friendly

C++ Intermediate | Mobile-Friendly

1. Data Types and Arrays
2. References & Pointers
3. Dynamic Memory
4. Functions

bookLoops 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:

12345678
int x[2][3]; for (int i = 0; i < 2; i++) { &nbsp;&nbsp;&nbsp;&nbsp; for (int j = 0; j < 3; j++) { &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; x[i][j] = rand() % 10; &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; cout << x[i][j] << " "; &nbsp;&nbsp;&nbsp;&nbsp; } } return 0;
copy

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.

We have the 3-dimensional array. How many for loops do we need to go through it?

We have the 3-dimensional array. How many for loops do we need to go through it?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 1. Capítulo 8
some-alt