Chapter 8. More Control Statements
Grammar, which knows how to control even kings . . .
At this point we know enough to create very simple programs. In this chapter we move on to more complex statements. For controlled looping we have the for statement. We also study the switch statement. This statement can be quite powerful and complex, but as we shall see in the following sections, if used right it can be very efficient and effective.
But we start our discussion with a new looping statement, the for.
for Statement
The for statement allows you to execute a block of code a specified number of times. The general form of the for statement is:
for (initial-statement;condition;iteration-statement)body-statement;
This is equivalent to:
initial-statement; while (condition) {body-statement;iteration-statement; }
For example, Example 8-1 uses a while loop to add five numbers.
Example 8-1. total6/total6w.cpp
#include <iostream>
int total; // total of all the numbers
int current; // current value from the user
int counter; // while loop counter
int main( ) {
total = 0;
counter = 0;
while (counter < 5) {
std::cout << "Number? ";
std::cin >> current;
total += current;
++counter;
}
std::cout << "The grand total is " << total << '\n';
return (0);
}The same program can be rewritten using a for statement, as seen in Example 8-2.
Example 8-2. total6/total6.cpp
#include <iostream> int total; // total of all the numbers int current; // current value from the user int counter; // for loop counter ...