April 5, 2008
WikiCounter-controlled repetition.
#wiki
Counter-controlled repetition.
1
2 // Counter-controlled repetition.
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
7 int main()
8 {
9 int counter = 1; // declare and initialize control variable
10
11 while ( counter <= 10 ) // loop-continuation condition
12 {
13 cout << counter << " ";
14 counter++; // increment control variable by 1
15 } // end while
16
17 cout << endl; // output a newline
18 return 0; // successful termination
19 } // end main
can be made more concise by initializing counter to 0 and by replacing the while statement with
while ( ++counter <= 10 ) // loop-continuation condition
cout << counter << " ";
This code saves a statement, because the incrementing is done directly in the while condition before the condition is tested. Also, the code eliminates the braces around the body of the while, because the while now contains only one statement. Coding in such a condensed fashion takes some practice and can lead to programs that are more difficult to read, debug, modify and maintain.
Continue Reading
Back to Archive