Java Project - Calculate Sum of Digits using Loop and Recursion
Java - Sum of Digits :
Sum of Digits:
Input: A number.
Output: Sum of the digits of the number.
Example:
- Input: 123
- Output: "Sum of digits: 6"
- Input: 4567
- Output: "Sum of digits: 22"
Solution 1: Sum of Digits using a While Loop
Code:
import java.util.Scanner;
public class SumOfDigits {
// Method to calculate the sum of digits using a while loop
public static int calculateSum(int number) {
int sum = 0;
// Loop until the number becomes 0
while (number != 0) {
sum += number % 10; // Add the last digit to sum
number = number / 10; // Remove the last digit
}
return sum;
}
// Main method to take user input and display the sum of digits
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking user input
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Calculating and displaying the sum of digits
int sum = calculateSum(number);
System.out.println("Sum of digits: " + sum);
scanner.close();
}
}
Output:
Enter a number: 345353 Sum of digits: 23
Enter a number: 00904320 Sum of digits: 18
Explanation :
- Input: User enters a number.
- Processing: The while loop extracts digits by taking the remainder of the division by 10, then adds the digit to the sum and removes it from the number.
- Output: The program prints the sum of the digits.
Solution 2: Sum of Digits using Recursion
Code:
import java.util.Scanner;
public class RecursiveSumOfDigits {
// Recursive method to calculate sum of digits
public static int calculateSum(int number) {
// Base case: If number is 0, return 0
if (number == 0) {
return 0;
}
// Recursive case: Add the last digit and call the method with the rest of the digits
return number % 10 + calculateSum(number / 10);
}
// Main method to take user input and display the sum of digits
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking user input
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Calculating and displaying the sum of digits
int sum = calculateSum(number);
System.out.println("Sum of digits: " + sum);
scanner.close();
}
}
Output:
Enter a number: 23423 Sum of digits: 14
Enter a number: 000000000 Sum of digits: 0
Explanation:
- Input: User inputs a number.
- Processing: Uses recursion to add the last digit to the result of the recursive call, which processes the remaining digits.
- Output: The program prints the sum of the digits.
Java Code Editor:
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/projects/java/java-project-calculate-sum-of-digits.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics