Reading Numbers Into an Array of Five

Medium

Chapter 2 summed a stream of numbers as they arrived, keeping nothing but a running total. This time keep the numbers themselves, in an array of exactly 5 ints, and report on them afterwards. The array and the two other variables are already declared, and so are the three printf lines at the bottom, so the whole exercise is the two loops between them. The first loop fills. Read numbers with scanf and store each one at values[count], then increment count so the next number lands in the next element, and stop for either of two reasons: the input stopped converting, or the array is full. Both reasons live in one condition, count < 5 && scanf("%d", &value) == 1, and the order of the two halves is not a matter of taste. && evaluates its left side first and skips the right side entirely when the left is false, so writing the capacity check first means that once count reaches 5 the scanf is never attempted at all. Write it the other way round and the sixth number is read into value and then stored at values[5], which is a write past the end of the array, undefined behaviour, and an AddressSanitizer stack-buffer-overflow that ends your program before it prints a thing. The second loop reports. It runs from 0 up to but not including count, and count rather than 5 is the bound because the elements past count were never filled and merely hold the zeroes the initializer put there; summing all five would quietly add numbers that were never in the input. Add each element to total, and compare each element against largest, replacing largest when the element is bigger. Notice that largest is already initialized to values[0] rather than to 0, which is what makes the negative test case come out right, and that reading values[0] is only safe because the count == 0 case returned before reaching it. Do not use a helper function: an array handed to a function is next lesson's subject and nothing about it is taught yet, so keep all of this in main. Every path returns 0, the no numbers read path included, because the checker reads a nonzero exit status as a failure however right the output looks.

Success Criteria

Your code must pass 6 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