Adding Up the Digits of a Number

Medium

Write one recursive function. main is already written and does not change: it reads a single number with scanf, rejects anything that is not a number and anything negative, and otherwise prints the digit sum. sum_digits takes an int that is zero or greater and returns the sum of its decimal digits, so 407 gives 11 because 4 plus 0 plus 7 is 11. Build it the way this lesson built countdown, base case first. A number below 10 is a single digit already, and a single digit is its own digit sum, so that call answers immediately without calling anything: that is the base case, and it is the only reason the chain of calls ever stops. Everything else splits into two smaller pieces with the two operators chapter 2 gave you, since n % 10 is the last digit of n and n / 10 is the whole number with that last digit removed, integer division throwing away the remainder. So the answer for a larger number is its last digit plus the digit sum of what is left, and that second half is a call to sum_digits itself on a strictly smaller number. Strictly smaller is the part that matters: n / 10 always moves toward the base case, which is why the recursion reaches it instead of running until AddressSanitizer reports a stack overflow. Each call gets its own frame holding its own n, so the n you read after the recursive call comes back is still the n this call started with, untouched by the deeper calls. Do not edit main, do not add a loop, and leave sum_digits above main where it is, because a definition placed after its call is a function the compiler has not heard of yet. Every path out of main returns 0, the two error paths included, because the checker compares what you print and reports a nonzero exit status as a failure however right the 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.

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