Two Functions That Take an Array and a Length
MediumLesson 1 kept everything in main because an array handed to a function had not been explained yet. Now it has, so this exercise moves the work out into two functions with the signature the rest of the course uses: int sum_values(const int *values, int count) returns the total of the elements, and int max_value(const int *values, int count) returns the largest of them. main is written for you and does not need changing. It fills an array of capacity 5 with the loop from lesson 1, keeps count beside it, prints no numbers read and returns when nothing converted, and otherwise calls your two functions and prints their results. Both functions arrive with a body that does a fraction of the job, and replacing that fraction with a loop over all count elements is the exercise. Read the signature before you start, because everything you need to know is in it. values is a pointer, not an array, and that is not a compromise the exercise made; it is what a function receives when an array is passed, since the array name decays to a pointer to its first element at the call. So do not reach for sizeof inside these functions. sizeof(values) is the size of a pointer, the familiar sizeof(values) / sizeof(values[0]) idiom computes 2 here no matter how many numbers were read, and a loop bounded by that answer would sum two elements and call it the total. count is the parameter that carries the length, and it is the only bound either loop may use. const is the other half of the signature and it is a promise: both functions read and neither writes, so if you accidentally assign to values[i] or to *p the compiler stops you with an error about a read-only location rather than letting the bug reach a caller. You may write either loop shape. The indexed form for (int i = 0; i < count; ++i) with values[i] is this course's default, and the pointer form for (const int *p = values; p < values + count; ++p) with *p visits exactly the same objects because values[i] is defined as *(values + i); writing one of each is a good way to prove to yourself that they are the same loop. max_value has one care that sum_values does not, the same one lesson 1's largest loop had: start largest at values[0] rather than at 0, or an input of nothing but negative numbers reports a largest that never appeared in it. Reading values[0] is safe here only because main returns before calling you when count is 0. Every path returns 0, since the checker treats a nonzero exit status as a failure however correct the printed output looks.
Success Criteria
Your code must pass 5 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.