Java Program to Find Sum of Digits in a Number using Recursion? Example (original) (raw)

Recently this question to ask was one of my readers, which inspired me to write this tutorial. There was a usual check to solve this problem using both recursion and iteration. To be frank, calculating the sum of digits of an integral number is not difficult, but I have still seen quite a few programmers fumbles, even after providing hints in terms of division and modulus operator. The key point here is to know how to use division and modulus operators in Java. This kind of exercise including reversing a number, where you need to find digits from a number, use division operator to remove right, and use modulus operator or % to get rightmost digits.

For example, if you have number 1234 then 1234/10 will give you 123 i.e. rightmost digit 4 is removed, while 1234%10 will give you 4, which is the rightmost digit in that number.

This is one of the important technique which is used to solve many coding problems like reverse an integer and check if the given number is palindrome or not.

Java program to calculate the sum of digits in a number

How to find sum of digit of a number coding question in JavaHere is a complete Java code example to find the sum of digits using recursion in Java. This Java example also includes an iterative solution to this problem to prepare follow-up questions from the Interviewer.

By the way, you can also use this example to learn Recursion in Java. It’s a tricky concept, and examples like this certainly help to understand and apply recursion better.

/**

}

Output: Sum of digit using recursion for number 123 is 6 Sum of digit using recursion for number 1234 is 10 Sum of digit from recursive function for number 321 is 6 Sum of digit from recursive method for number 1 is 1 Sum of digit using Iteration for number 123 is 6 Sum of digit using while loop for number 1234 is 10

That's all on How to find the sum of digits of a number using recursion in Java. You should be able to write this method using both Iteration i.e. using loops, and using Recursion i.e. without using loops in Java.

And now is the quiz time, What is the time complexity of this algorithm to find the sum of digits in a given integer number? can you improve this by using any data structure or different approach?