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

Course Content

C++ Intermediate | Mobile-Friendly

C++ Intermediate | Mobile-Friendly

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

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

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

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 1. ChapterΒ 8
We're sorry to hear that something went wrong. What happened?
some-alt