Programming Example-8
Nested Control Structures (Patterns):
Suppose you want to create the following pattern:
*
**
***
****
*****
Clearly, you want to print five lines of stars. In the first line, you want to print one star, in the second line, two stars, and so on. Because five lines will be printed, start with the following for statement:
for (i = 1; i <= 5; i++)
The value of i in the first iteration is 1, in the second iteration it is 2, and so on. You can use the value of i as the limiting condition in another for loop nested within this loop to control the number of stars in a line. A little more thought produces the following code:
for (i = 1; i <= 5; i++)
{
for (j = 1; j <= i; j++)
cout << "*";
cout << endl;
}
A walk-through of this code shows that the for loop in Line 1 starts with i = 1. When i is 1, the inner for loop in Line 3 outputs one star and the insertion point moves to the next line. Then i becomes 2, the inner for loop outputs two stars, and the output statement in Line 5 moves the insertion point to the next line, and so on. This process continues until i becomes 6 and the loop stops.
What pattern does this code produce if you replace the for statement in Line 1 with the
following?
for (i = 5; i >= 1; i--)
Comments
Post a Comment