|
|
 |
|
|
|
|
while (1)
cout << H << endl; |
|
|
|
 |
|
|
|
|
Both of these are infinite loops that print Hi endlessly. |
|
|
|
|
|
|
|
|
3. The initializing statement, InitStatement, can be a declaration with initialization: |
|
|
|
 |
|
|
|
|
for (int i = 1; i <= 20; i++)
cout << Hi << endl; |
|
|
|
 |
|
|
|
|
But you have to be careful here. The variable i is not local to the body of the loop. Its scope extends to the end of the block surrounding the For statement. In other words, it's as if i had been declared outside the loop. The following sequence of statements, therefore, produces a compiletime error: |
|
|
|
 |
|
|
|
|
for (int i = 1; i <= 20; i++)
cout << Hi << endl;
for (int i = 1; i <= 100; i++) // Error--i already defined
cout << Ed << endl; |
|
|
|
|
|
|
|
|
As you have seen by now, the For statement in C++ is a very flexible structure. Its use can range from a simple count-controlled loop to a generalpurpose, anything goes While loop. Some programmers find it an intellectual challenge to see how much they can squeeze into the heading (the first line) of a For statement. For example, the program fragment |
|
|
|
|
|
|
|
|
cin >> ch;
while (ch != .)
cin >> ch; |
|
|
|
|
|
|
|
|
can be compressed into the following For loop: |
|
|
|
|
|
|
|
|
for (cin >> ch; ch != .; cin >> ch)
; |
|
|
|
|
|
|
|
|
Because all the work is done in the For heading, there is nothing for the loop body to do. The body is simply the null statement. |
|
|
|
|
|
|
|
|
With For statements, our advice is to keep things simple. The trickier the code is, the harder it will be for another person (or you!) to understand your code and track down errors. In this book, we use For loops for countcontrolled loops only. |
|
|
|
|
|