August 2012
Intermediate to advanced
976 pages
30h 17m
English
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 ...
Read now
Unlock full access