Process numbers without knowing how many there are.
What to build
A program that reads until the input runs out.
Requirements
- Read whole numbers until the input ends.
- Print
count C,sum Sandmax M. - Print
no dataif there were no numbers.
Input
Whole numbers separated by spaces or new lines. There may be none.
Output
Three lines, or no data.
Constraints
There are at most 100000 numbers, each from -1000000 to 1000000.
Example
Input:
1 2 3
Output:
count 3
sum 6
max 3
Why it works
A failed read turns the condition false, so the same loop works for any amount of input. The largest value starts from the first number read, so negative numbers work too.
Examples
Example 1 · Input
1 2 3
Expected output
count 3 sum 6 max 3
Example 2 · Input
-5 -2
Expected output
count 2 sum -7 max -2
Hints
Hint 1
Use while (cin >> x).
Hint 2
Keep a count, a sum and the largest so far.
Hint 3
If the count is 0, nothing was read.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
int main() {
int x, count = 0, best = 0;
long long sum = 0;
while (cin >> x) {
if (count == 0 || x > best) {
best = x;
}
count++;
sum += x;
}
if (count == 0) {
cout << "no data" << endl;
} else {
cout << "count " << count << endl;
cout << "sum " << sum << endl;
cout << "max " << best << endl;
}
return 0;
}