< previous page page_470 next page >

Page 470
for (lastNum = 1; lastNum <= 7; lastNum++)
{
    for (numToPrint = 1; numToPrint <= lastNum; numToPrint++)
        cout << numToPrint;
    cout << endl;
}
prints the following triangle of numbers.
1
12
123
1234
12345
123456
1234567
Although For statements are used most frequently for count-controlled loops, C++ allows you to write any While loop by using a For statement. To use For loops intelligently, you should know the following facts.
1. In the syntax template, InitStatement can be the null statement, and Expression2 is optional. If Expression2 is omitted, there is no statement for the compiler to insert at the bottom of the loop. As a result, you could write the While loop
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
while (inputVal != 999)
    cin >> inputVal;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
as the equivalent For loop
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
for ( ; inputVal != 999; )
     cin >> inputVal;
2. According to the syntax template, Expression1the While conditionis optional. If you omit it, the expression 1 (meaning TRUE) is assumed.
The loop
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
for ( ; ; )
    cout H  << endl;
3e26ecb1b6ac508ae10a0e39d2fb98b2.gif
is equivalent to the While loop

 
< previous page page_470 next page >