Examples
- Hello World Program in Java (Print Hello World in Java)
- Java Program to Add Two Numbers (Java Sum / Addition)
- Find Greatest of Three Numbers in Java (Largest Number Program)
- Prime Number Program in Java (Code to Check Prime or Not)
- Java Program for Fibonacci Series (Using for, while, recursion, scanner)
- Factorial Program in Java (Find Factorial of a Number in Java)
- How to Find Sum of Digits of a Number in Java?
- How to Reverse a Number in Java? Program & Examples
- How to Swap Two Numbers in Java? Programs With/Without Third Variable
- Even Odd Program in Java (Program to Check Number is Even or Odd)
- Vowel and Consonant Program in Java
- Java Program for Quadratic Equation (Find Roots With 3 Ways)
- Find Frequency of Characters in a String in Java (4 Ways)
- Remove Space from String in Java (Remove Whitespace)
- String Null Check in Java (String is Empty or Null) - 5 Ways
- How to Print String in Java? 6 Methods
- How to Get ASCII Value of Char in Java? Find ASCII Value
How to Find Sum of Digits of a Number in Java?
Let’s learn the multiple ways to find the sum of digits of a number in Java!
The sum of digits is a common mathematical operation that involves adding up all the individual digits in a given number. Understanding different techniques to find the sum of digits in Java is essential for various applications, ranging from verifying the validity of identification numbers to solving complex maths problems.
Here, you will know and understand the different ways to calculate the sum of digits of a number in Java. Each method offers its own unique advantages, enabling you to choose the most suitable approach for specific scenarios and optimize your code for efficiency.
So, let’s get started and practice the Java program for sum of digits of a number!
Sum of Digits in Java Using while loop
The following program calculates the sum of digits of number in Java using loop:
Code
import java.util.Scanner;
public class SumOfDigitsCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number < 0) {
System.out.println("Please enter a non-negative integer.");
} else {
int sumOfDigits = calculateSumOfDigits(number);
System.out.println("Sum of digits of " + number + " is: " + sumOfDigits);
}
}
private static int calculateSumOfDigits(int n) {
int sum = 0;
while (n != 0) {
int digit = n % 10; // Extract the last digit of the number
sum += digit; // Add the digit to the sum
n /= 10; // Remove the last digit from the number
}
return sum;
}
}
Output
Enter a number: 678
Sum of digits of 678 is: 21
Explanation
In this program, we use the Scanner class to take input from the user. The user is prompted to enter a number, and the program calculates the sum of its digits using a while loop.
The calculateSumOfDigits method takes an integer n as input and initializes a variable sum to store the sum of digits. In the while loop, we extract the last digit of the number using the modulo operator %, add it to the sum, and then remove the last digit from the number by dividing it by 10.
This process continues until all the digits have been processed, and the sum of all digits is calculated and returned.
Sum of Digits in Java Using Recursion
Here's a Java program that calculates the sum of digits of a given number using recursion:
Code
import java.util.Scanner;
public class SumOfDigitsCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a non-negative integer: ");
int number = scanner.nextInt();
if (number < 0) {
System.out.println("Please enter a non-negative integer.");
} else {
int sumOfDigits = calculateSumOfDigits(number);
System.out.println("Sum of digits of " + number + " is: " + sumOfDigits);
}
}
private static int calculateSumOfDigits(int n) {
if (n < 10) {
return n; // Base case: If n is a single-digit number, return itself
} else {
return n % 10 + calculateSumOfDigits(n / 10); // Recursive case: Add last digit and call recursively for remaining digits
}
}
}
Output
Enter a number: 4728
Sum of digits of 4728 is: 21
Explanation
In this program, we use recursion to calculate the sum of digits of a given number. The calculateSumOfDigits method takes an integer n as input.
The base case is when n is a single-digit number (i.e., less than 10). In the base case, the method returns n itself, as the sum of a single-digit number is the number itself.
The recursive case is when n is greater than or equal to 10. In the recursive case, we calculate the sum of the last digit of n (obtained using % 10) and the sum of digits of the remaining part of n (obtained using / 10) by making a recursive call to the calculateSumOfDigits method.
This process continues until n becomes a single-digit number, and the sum of all digits is calculated and returned.
Learn Next: