Nested loops, did not manage to do the exercise

Hello,
I am not sure where to find support. I don’t understand Nested Loops on C++. I watched the video and did not manage to do the exercise. Can anyone explain me, please?

Which exercise? Do you have some code which is not working? As written your question basically asks “complete the exercise for me” so if you can ask for clarification on a more specific point it is easier for us to help.

Yes it was this exercise:
#include
#include
using namespace std;
int main() {
cout << left;
int rows;
cout << "Enter number of rows: ";
cin >> rows;
for (int i = 1; i <= rows ; i++){
for (int j = 0 ; j < i ; j++)
cout << “*”;
cout << endl;
}
return 0;}

I don’t understand how the code is able to print
*
**




It was in the first video of C++ for the basics

Hi Magnon, thank you for asking this question. I have just got up to this lesson and it stumped me for a while. Perhaps the following will help.

Inner for loop: -

for (int j = 0; j < i; j++ )

cout << “*”;

This just keeps outputting an * for as long as j is less than i.

So, when j equals 0 then the cout is *

and when j increments to 1 then the cout puts another * next to the one already there so the display is **. All this is on one line.

Obviously, this happens a lot quicker in real time and you do not see it in slow motion.

The problem is that you need to have one * on the first line, followed by two ** on another new line so that the output looks like: -
*
**

This is where the Outer Loop is used to advance the line by using endl.

The outer loop code is: -

For (int i = 1; i <= rows; i++){
Run the Inner loop code
cout << endl;
}

The outer loop runs as follows, assume rows = 2: -

Step 1: - The outer for loop value for i = 1. This is passed to the inner loop. In the first iteration of the inner loop, j = 0, i = 1 and the cout is *

Step 2: - Then the inner loop j increments to j = 1, i stays the same at i = 1 and the inner loop stops because j < i (1 < 1 is false).

Step 3: - Control goes back to the outer loop and this is where the endl is used to move to the next line.

Step 4: - Then the value of i increases to 2.

Step 5: - This value is passed to the inner loop where j has been reset to 0.

Step 6: - The inner loop cout’s a * because j = 0 and i = 2. But wait, when j increments to 1 the conditional (j < i) 1 < 2 is still true.

So another * is placed next to the one already there. We now have **.

Step 7: - The inner loop value for j increments to a value of 2 and the conditional fails (2<2) is false so the inner loop stops and the cout is **

Step 8: - The last part of the outer loop code is endl so this sets up for the next line (if there was one).

Step 9: - Control is passed back to the outer loop and i increments to 3. However, the conditional i <= rows fails because 3 <= 2 is false.

The output is: -

**

Hope that helps,
Paul

1 Like