Sum of Digits of a Number using Recursion – Java Code

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)

Find sum of digits of a number using recursion

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.

Programming video tutorials

 

The other similar problem find sum of array elements using recursion.

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.