Recursion · 13 / 18 Exercise Easy

Sum of digits

Objective

A sum of digits has a natural recursive definition: the sum of a number is its last digit plus the sum of the rest of the number.

Instructions

  • Define sum_digits(n) recursively: if n has a single digit (n < 10) return n; otherwise return n % 10 + sum_digits(n // 10).
  • Read k and then k non-negative integers, one per line.
  • For each one show n: sum. Do not use loops or convert the number into text.
Input
3
123
9
9875
Output
123: 6
9: 9
9875: 29

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise