Reading a Stream of Numbers Until It Stops

Easy

Read whole numbers from the input with while (scanf("%d", &value) == 1) until the input stops converting, keeping three running values as you go: how many numbers arrived, their total, and the largest of them. When the loop ends, report. If nothing converted at all, print "no numbers read" and stop there. Otherwise print exactly three lines, "count: 3", then "sum: 16", then "max: 9". The loop is the easy part of this exercise. The two hard parts are both about what happens around it. The accumulators have to be declared and zeroed above the loop, because the loop body cannot report anything and the report cannot see anything the loop kept to itself. And the maximum cannot start at 0: one of the test cases is nothing but negative numbers, and a max that starts at 0 would announce 0 as the largest number in a stream that never contained it. Take the maximum from the first value that actually arrives instead. The total is a long because a stream of unknown length is exactly where int addition would overflow, so print it with %ld and not %d. Every run of this program ends with return 0, including the empty one; the checker compares what you print, and a nonzero exit status is reported as a failure no matter how right the output looks.

Success Criteria

Your code must pass 4 test case(s) to complete this exercise. 3 hint(s) are available if you need help.

Sign in to track your progress

You can work on exercises as a guest, but sign in to track your progress and save your submissions.

This platform is built by its community

Every lesson, project, and tool on HelloC++ is funded by sponsors. Join them and help shape what we build next.

Become a Patron