< previous page page_127 next page >

Page 127
What character?  x
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx
Analysis: The user is prompted for the number of rows and columns and for a character to print. The first for loop, on line 16, initializes a counter (i) to 0, and then the body of the outer for loop is run.
On line 18, the first line of the body of the outer for loop, another for loop, is established. A second counter (j) is also initialized to 0, and the body of the inner for loop is executed. On line 19, the chosen character is printed, and control returns to the header of the inner for loop. Note that the inner for loop is only one statement (the printing of the character). The condition is tested (j < columns); if it evaluates to true, j is incremented and the next character is printed. This continues until j equals the number of columns.
When the inner for loop fails its test, in this case after 12 xs are printed, execution falls through to line 20, and a new line is printed. The outer for loop now returns to its header, where its condition (i < rows) is tested. If this evaluates to true, i is incremented and the body of the loop is executed.
In the second iteration of the outer for loop, the inner for loop is started over. Thus j is reinitialized to 0 (!), and the entire inner loop is run again.
The important idea here is that by using a nested loop, the inner loop is executed for each iteration of the outer loop. Thus the character is printed columns times for each row.
switch Statements
if and elseif combinations can become quite confusing when nested too deeply, and C++ offers an alternative. Unlike if, which evaluates one value, switch statements enable you to branch on any of a number of different values. The general form of the switch statement is
switch (expression)
{
case valueOne: statement;
                   break;
case valueTwo: statement;
                   break;
.
case valueN:   statement;
                   break;
default:      statement;
}

 
< previous page page_127 next page >

If you like this book, buy it!