Nested loop assistance

3 weeks ago 27
ARTICLE AD BOX

Your inner loop is using the wrong logic.

On the 1st iteration of the outer loop, the inner loop iterates 1..5, printing both rows and a newline 5 times.

On the 2nd iteration of the outer loop, the inner loop iterates 2..5, printing both rows and a newline 4 times.

On the 3rd iteration of the outer loop, the inner loop iterates 3..5, printing both rows and a newline 3 times.

On the 4th iteration of the outer loop, the inner loop iterates 4..5, printing both rows and a newline 2 times.

On the 5th iteration of the outer loop, the inner loop iterates 5..5, printing both rows and a newline 1 time.

In all iterations, line can never be less than rows, so - is never printed.

To meet your requirements, the logic needs to be more like this instead:

On the 1st iteration of the outer loop, the inner loop iterates 1..1, printing just rows 1 time, and then print a newline after the inner loop.

On the 2nd iteration of the outer loop, the inner loop iterates 1..2, printing just rows 2 times, and then print a newline after the inner loop.

On the 3rd iteration of the outer loop, the inner loop iterates 1..3, printing just rows 3 times, and then print a newline after the inner loop.

On the 4th iteration of the outer loop, the inner loop iterates 1..4, printing just rows 4 times, and then print a newline after the inner loop.

On the 5th iteration of the outer loop, the inner loop iterates 1..5, printing just rows 5 times, and then print a newline after the inner loop.

And your code should look like the following:

#include <iostream> using namespace std; int main() { for (int row = 1; row <= 5; row++) { for (int count = 1; count <= row; count++) { cout << row << ' '; } cout << endl; } return 0; }

Online Demo

If you don't want the extra space before each newline, you can do this instead:

#include <iostream> using namespace std; int main() { for (int row = 1; row <= 5; row++) { for (int count = 1; count <= row; count++) { if (count > 1) { cout << ' '; } cout << row; } cout << endl; } return 0; }

Online Demo

Alternatively:

#include <iostream> using namespace std; int main() { for (int row = 1; row <= 5; row++) { cout << row; for (int count = 2; count <= row; count++) { cout << ' ' << row; } cout << endl; } return 0; }

Online Demo

Read Entire Article