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.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.