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

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.

question mark

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

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 8

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Awesome!

Completion rate improved to 2.94

bookLoops thought Multi-Dimensional Arrays

Svep för att visa menyn

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.

question mark

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

Select the correct answer

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 8
some-alt