Statements normally execute sequentially: The first statement in a block is executed first, followed by the second, and so on. Of course, few programs—including the one to solve our bookstore problem—can be written using only sequential execution. Instead, programming languages provide various flow-of-control statements that allow for more complicated execution paths.
1.4.1 The while Statement
A while statement repeatedly executes a section of code so long as a given condition is true. We can use a while to write a program to sum the numbers from 1 through 10 inclusive as follows:
- #include <iostream>
- int main()
- {
- int sum = 0, val = 1;
-
- while (val <= 10) {
- sum += val;
- ++val;
- }
- std::cout << "Sum of 1 to 10 inclusive is "
- << sum << std::endl;
- return 0;
- }
When we compile and execute this program, it prints
- Sum of 1 to 10 inclusive is 55
As before, we start by including the iostream header and defining main. Inside main we define two int variables: sum, which will hold our summation, and val, which will represent each of the values from 1 through 10. We give sum an initial value of 0 and start val off with the value 1.
The new part of this program is the while statement. A while has the form
- while (condition)
- statement
A while executes by (alternately) testing the condition and executing the associated statement until the condition is false. A condition is an expression that yields a result that is either true or false. So long as condition is true, statement is executed. After executing statement, condition is tested again. If condition is again true, then statement is again executed. The while continues, alternately testing the condition and executing statement until the condition is false.