EXERCISES SECTION 1.4.1
Exercise 1.9: Write a programthat uses a while to sum the numbers from50 to 100.
Exercise 1.10: In addition to the ++ operator that adds 1 to its operand, there is a decrement operator (--) that subtracts 1. Use the decrement operator to write a while that prints the numbers from ten down to zero.
Exercise 1.11: Write a program that prompts the user for two integers. Print each number in the range specified by those two integers.
1.4.2 The for Statement
In our while loop we used the variable val to control how many times we executed the loop. We tested the value of val in the condition and incremented val in the while body.
This pattern—using a variable in a condition and incrementing that variable in the body—happens so often that the language defines a second statement, the for statement, that abbreviates code that follows this pattern. We can rewrite this program using a for loop to sum the numbers from 1 through 10 as follows:
- #include <iostream>
- int main()
- {
- int sum = 0;
-
- for (int val = 1; val <= 10; ++val)
- sum += val;
- std::cout << "Sum of 1 to 10 inclusive is "
- << sum << std::endl;
- return 0;
- }
As before, we define sum and initialize it to zero. In this version, we define val as part of the for statement itself:
- for (int val = 1; val <= 10; ++val)
- sum += val;
Each for statement has two parts: a header and a body. The header controls how often the body is executed. The header itself consists of three parts: an initstatement, a condition, and an expression. In this case, the init-statement
- int val = 1;
defines an int object named val and gives it an initial value of 1. Thevariableva l exists only inside the for; it is not possible to use val after this loop terminates. The init-statement is executed only once, on entry to the for. The condition
- val <= 10
compares the current value in val to 10. The condition is tested each time through the loop. As long as val is less than or equal to 10, we execute the for body. The expression is executed after the for body. Here, the expression
- ++val
uses the prefix increment operator, which adds 1 to the value of val. After executing the expression, the for retests the condition. If the new value of val is still less than or equal to 10, then the for loop body is executed again. After executing the body, val is incremented again. The loop continues until the condition fails.
In this loop, the for body performs the summation
- sum += val;
To recap, the overall execution flow of this for is:
1. Create val and initialize it to 1.
2. Test whether val is less than or equal to 10. If the test succeeds, execute the for body. If the test fails, exit the loop and continue execution with the first statement following the for body.
3. Increment val.
4. Repeat the test in step 2, continuing with the remaining steps as long as the
condition is true.