Write a java program to find sum of digits of a number using recursion. Given a number, Write a java code to calculate sum of digits of a number using recursion.
For example –
Input number : 123
Output : 6 (1 + 2 + 3)
In my previous tutorial, I have explained how to find sum of digit of a number using iterative approach. In this tutorial, we areĀ going to learn how we can do it using recursion.
Find Sum of Digits of a Number using Recursion – Java Code
To calculate sum of digits of a number recursively. We have written one method (sumOfDigits(int num)) which takes integer as an argument and calculate it’s sum recursively.
For better understanding of this code and how it works i have added video tutorial at the end of this post.
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 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); } } |
In this video tutorial, I have explained how you can write a java code to find sum of digits of a number recursively.