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).