How to find the output of this nested loop

This input and output is from a textbook:

for (row = 0; row < 3; row++)
{
for (star = 0; star < 20; star++)
{
cout << '*';
if (star == 10)
break;
}
cout << endl;
}

The output of this program segment is
***********
***********
***********

This nested loop program confuses me. I would appreciate it if someone could explain why there are 11 asterisks in all three rows if the if statement writes (star == 10) in the inner loop. I am not sure how to find the output on my own.
Your code outputs an asterisk and then checks if star equals 10, So it will output an asterisk for star ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8 , 9, 10} — 11 elements.
inner loop:
star = 0, print a star (1 star in the row now)
star = 1, print a star (2 stars in the row now)
star = 2, print a star (3 stars in the row now)
star = 3, print a star (4 stars in the row now)
star = 4, print a star (5 stars in the row now)
star = 5, print a star (6 stars in the row now)
star = 6, print a star (7 stars in the row now)
star = 7, print a star (8 stars in the row now)
star = 8, print a star (9 stars in the row now)
star = 9, print a star (10 stars in the row now)
star = 10, print a star (11 stars in the row now) AND THEN BREAK!

The outer loop executes the inner loop and then prints a new line. That's why there are 3 rows of 11 stars.

The thing to note is that it doesn't count from ONE to ten (ten steps).
It counts from ZERO to ten ( eleven steps).

EDIT: MiiNiPaa beat me to it. Brevity FTW!
Last edited on
Thank you. But, the if statement still troubles me. If I were to change the relational operator in the if statement as such,

for (row = 0; row < 3; row++)
{
for (star = 0; star < 20; star++)
{
cout << '*';
if (star <= 10)
break;
}
cout << endl;
}

Why would the output of this program segment be
*
*
*
1st iteration: star = 0, print a asterisk, check if star <= 10... TRUE, break inner loop. No second iteration for you.
Last edited on
Thank you so much! I understand now.
Last edited on
Topic archived. No new replies allowed.