The program of Fig. 5.5 uses a for
statement to sum the even integers from 2 to 20. Each iteration of the loop (lines 11–12) adds control variable number
’s value to variable total
.
1 // Fig. 5.5: fig05_05.cpp
2 // Summing integers with the for statement.
3 #include <iostream>
4 using namespace std;
5
6 int main()
7 {
8 unsigned int total = 0; // initialize total
9
10 // total even integers from 2 through 20
11 for ( unsigned int number = 2; number <= 20; number += 2 )
12 total += number;
13
14 cout << "Sum is " << total << endl; // display results
15 } // end main
Sum is 110
The body of the for
statement in Fig. 5.5 actually could be merged into the increment portion of the for
header by using the comma operator as follows:
for ( unsigned int number = 2; // initialization
number <= 20; // loop continuation condition
total += number, number += 2 ) // total and increment
; // empty body
Good Programming Practice 5.1
Although statements preceding a for and statements in the body of a for often can be merged into the for header, doing so can make the program more difficult to read, maintain, modify and debug.
18.217.228.35