Program to Find the Sum of Digits of a Number in Java
Finding the Sum of Digits
The sum of digits of a number is calculated by repeatedly extracting each digit and adding it to a sum variable.
We will explore a method to compute the sum of digits using Java programming.
Method: Using a while Loop
We extract each digit using the modulus operator and sum them up.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int num = scanner.nextInt(); int sum = 0, digit; // Loop to extract and sum digits while (num > 0) { digit = num % 10; // Extract last digit sum += digit; // Add digit to sum num /= 10; // Remove last digit from number } // Print the result System.out.println("Sum of digits = " + sum); scanner.close(); } }
Output:
Enter a number: 1234 Sum of digits = 10