Java Recursive Method: Find the sum of digits in an integer
Java Recursive: Exercise-14 with Solution
Write a Java recursive method to find the sum of the digits of a given integer.
Sample Solution:
Java Code:
public class DigitSumCalculator {
public static int calculateDigitSum(int number) {
// Base case: if the number is a single digit, return the number itself
if (number < 10) {
return number;
}
// Recursive case: calculate the sum of the last digit and the digit sum of the remaining number
int lastDigit = number % 10;
int remainingNumber = number / 10;
return lastDigit + calculateDigitSum(remainingNumber);
}
public static void main(String[] args) {
int number = 123456;
int digitSum = calculateDigitSum(number);
System.out.println("The sum of the digits of " + number + " is: " + digitSum);
}
}
Sample Output:
The sum of the digits of 123456 is: 21
Explanation:
In the above exercises -
First, we define a class "DigitSumCalculator" that includes a recursive method calculateDigitSum() to find the sum of the digits of a given integer number.
The calculateDigitSum() method has two cases:
- Base case: If the number is a single digit (less than 10), we return the number itself as the sum of its digits.
- Recursive case: For any number with more than one digit, we calculate the last digit by taking the number modulo 10. We then calculate the sum of the last digit and the digit sum of the remaining number obtained by dividing the number by 10. This process continues until the number is reduced to a single digit.
In the main() method, we demonstrate the calculateDigitSum() method by finding the sum of the digits of the number 12345 and printing the result.
Flowchart:
Java Code Editor:
Java Recursive Previous: Calculate the product of numbers in an array.
Java Recursive Next: Check ascending order.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/recursive/java-recursive-exercise-14.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics