Write a Java Program to Sum Digits in an Integer

How can we write a Java program that reads an integer between 0 and 1000 and adds all the digits in the integer?

Java Program to Sum Digits in an Integer

Here's a Java program that takes an integer between 0 and 1000 as input, adds all the digits in the integer, and then displays the sum:


        import java.util.Scanner;
        
        public class SumOfDigits {
            public static void main(String[] args) {
                Scanner scanner = new Scanner(System.in);
                System.out.print("Input an integer between 0 and 1000: ");
                int num = scanner.nextInt();
                
                if (num < 0 || num > 1000) {
                    System.out.println("Please enter a valid integer between 0 and 1000.");
                } else {
                    int sum = 0;
                    int originalNum = num;
                    
                    while (num > 0) {
                        int digit = num % 10; // Get the last digit
                        sum += digit; // Add the digit to the sum
                        num /= 10; // Remove the last digit
                    }
                    System.out.println("The sum of all digits in " + originalNum + " is " + sum);
                }
                scanner.close();
            }
        }
    

Explanation

Java Program:

This Java program reads an integer input between 0 and 1000 from the user. It then checks if the input is within the valid range. If the input is valid, it extracts each digit from the integer using a while loop.

Inside the while loop:

  • We get the last digit of the number using the modulo (%) operator.
  • We add this digit to the sum variable.
  • We remove the last digit by dividing the number by 10.

The loop continues until the number becomes 0. Finally, the program displays the sum of all digits in the original number.

When the program is run with an input of 565, it outputs "The sum of all digits in 565 is 16."

← How to create and organize files for path of light yoga studio website How to choose the right smartphone →