In this tutorial, I am going to discuss programming questions to find the sum of digits of a number using recursion.
Given a positive number, Write a java code to calculate the sum of digits of a number using recursion.
For example –
Input number: 123
Output : 6 (1 + 2 + 3)
In my previous tutorial, I have already explained how to find sum of digit of a number using an iterative approach. In this tutorial, we are going to solve this problem using recursion.
If you are not familiar with recursion then please check my previous tutorials’ recursion vs iteration.
Programming questions on recursion
Find Sum of Digits of a Number using Recursion – Java Code
We have to calculate the sum of digits using recursion. Before solving this problem, let’s quickly refresh the concept of recursion.
In recursion, the function calls itself until the base condition is not reached. So, let’s first define the base condition. The base condition is if the number is zero then simply return 0. Else extract one digit at a time and recursively call the method with the number reduced by 10.
Let’s understand this through example. Suppose we have to calculate the sum of 123 using recursion.
Initially, we call a method sumOfDigits(123).
This number is not equal to zero. Let’s extract the last digit of this number and recursively call this method with the new number.
sumOfDigits(123)
3 + sumOfDigits(12)
2 + sumOfDigits(1)
1 + sumOfDigits(0)
0
I have also created a video tutorial to find the sum of digits of a number using recursion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/** * Find sum of digits of a number using recursion */ public class SumOfDigitsRecursion { private static int sumOfDigits(int num) { //If num zero then return 0 if(num == 0) { return 0; } //recursive call return num % 10 + sumOfDigits(num/10); } public static void main(String[] args) { //Calling sumOfDigits method int result = sumOfDigits(1234); //Print result System.out.println(result); } } |
The other similar problem find sum of array elements using recursion.