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
Easy aceess next quctions
Getting Started

Positive or Negative number: C C++ Java Python

Even or Odd number: C C++ Java Python

Sum of First N Natural numbers: C C++ Java Python

Sum of N natural numbers: C C++ Java Python

Sum of numbers in a given range: C C++ Java Python

Greatest of two numbers: C C++ Java Python

Greatest of the Three numbers: C C++ Java Python

Leap year or not: C C++ Java Python

Prime number: C C++ Java Python

Prime number within a given range: C C++ Java Python

Sum of digits of a number: C C++ Java Python

Reverse of a number: C C++ Java Python

Palindrome number: C C++ Java Python

Armstrong number: C C++ Java Python

Armstrong number in a given range: C C++ Java Python

Harshad number: C C++ Java Python

Abundant number: C C++ Java Python

Friendly pair: C C++ Java Python