VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-digit-number-using-recursion/

⇱ Sum of digit of a number using recursion - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of digit of a number using recursion

Last Updated : 17 Mar, 2025

Given a number, we need to find sum of its digits using recursion.

Examples: 

Input: 12345
Output: 15
Explanation: Sum of digits → 1 + 2 + 3 + 4 + 5 = 15

Input: 45632
Output: 20

Approach:

To understand the algorithm, consider the number 12345 and refer to the illustration below..

  • Extract the last digit: 12345 % 10 = 5, pass 1234 to the next step.
  • Extract next digit: 1234 % 10 = 4, pass 123 to the next step.
  • Extract next digit: 123 % 10 = 3, pass 12 to the next step.
  • Extract next digit: 12 % 10 = 2, pass 1 to the next step.
  • Extract last digit: 1 % 10 = 1, pass 0, stopping recursion.

Each step adds the extracted digit to the sum, forming 1 + 2 + 3 + 4 + 5 = 15

👁 sum-of-digit
Recursive Sum of Digits for 12345

Note: Instead of if (n == 0) return 0;, we can use if (n < 10) return n;, eliminating extra function calls for single-digit numbers without changing the output.


Output
15

Besides writing (n==0 , then return 0) in the code given above we can also write it in this manner , there will be no change in the output .

if (n <1 0) return n; by writing this there will be no need to call the function for the numbers which are less than 10

Time Complexity: O(log10n), Traverse through all the digits, as there are log10n bits.
Auxiliary Space: O(log10n), due to recursive function calls stored in the call stack.

Comment
Article Tags: