EXERCISES SECTION 1.4.2
Exercise 1.12: What does the following for loop do What is the final value of sum
- int sum = 0;
- for (int i = -100; i <= 100; ++i)
- sum += i;
Exercise 1.13: Rewrite the exercises from § 1.4.1 (p. 13) using for loops.
Exercise 1.14: Compare and contrast the loops that used a for with those using a while. Are there advantages or disadvantages to using either form
Exercise 1.15: Write programs that contain the common errors discussed in the box on page 16. Familiarize yourself with the messages the compiler generates.
1.4.3 Reading an Unknown Number of Inputs
In the preceding sections, we wrote programs that summed the numbers from 1 through 10. A logical extension of this program would be to ask the user to input a set of numbers to sum. In this case, we won’t know how many numbers to add. Instead, we’ll keep reading numbers until there are no more numbers to read:
- #include <iostream>
- int main()
- {
- int sum = 0, value = 0;
- // read until end-of-file, calculating a running total of all values read
- while (std::cin >> value)
- sum += value; // equivalent to sum = sum + value
- std::cout << "Sum is: " << sum << std::endl;
- return 0;
- }
If we give this program the input
- 3 4 5 6
then our output will be
- Sum is: 18
The first line inside main defines two int variables, named sum and value, which we initialize to 0. We’ll use value to hold each number as we read it from the input. We read the data inside the condition of the while:
- while (std::cin >> value)
eva luating the while condition executes the expression
- std::cin >> value
That expression reads the next number from the standard input and stores that number in value. The input operator (§ 1.2, p. 8) returns its left operand, which in this case is std::cin. This condition, therefore, tests std::cin.
When we use an istream as a condition, the effect is to test the state of the stream. If the stream is valid—that is, if the stream hasn’t encountered an error— then the test succeeds. An istream becomes invalid when we hit end-of-file or encounter an invalid input, such as reading a value that is not an integer. An istream that is in an invalid state will cause the condition to yield false.
Thus, our while executes until we encounter end-of-file (or an input error). The while body uses the compound assignment operator to add the current value to the evolving sum. Once the condition fails, the while ends. We fall through and execute the next statement, which prints the sum followed by endl.