Example 48: The Sum of the Digits of a Number
Learn how to calculate the sum of the digits of a number using recursion.
We'll cover the following
Problem
Write a recursive function that takes in a positive integer as input and calculates the sum of its digits.
Example
Input | Output |
---|---|
0 | 0 |
5 | 5 |
345 | 12 |
5420 | 11 |
Try it yourself
Try to solve this question on your own in the code widget below. If you get stuck, you can always refer to the solution provided.
Get hands-on with 1400+ tech skills courses.