110k views
1 vote
Write a program that reads an integer between 0 and 999 and adds all the digits in the integer. For example, if the input is 932, the sum of its digits is 14. in Java.

1 Answer

6 votes

Final answer:

The student's question is about writing a Java program that sums the digits of an integer between 0 and 999. A while loop is used to extract each digit and compute the sum. The program continues until the integer is reduced to zero.

Step-by-step explanation:

Java Program to Sum Digits of an Integer

When handling numbers in the range of 0 to 999, a Java program can easily compute the sum of all the digits in a given integer. To accomplish this, we can use a simple while loop that repeatedly extracts each digit by taking the remainder of division by 10 and then dividing the number by 10 to remove the extracted digit. This process continues until the number becomes zero.

Java Example:

Here is a sample Java program:

import java.util.Scanner;

class DigitsSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer between 0 and 999: ");
int number = input.nextInt();
int sum = 0;

while (number > 0) {
sum += number % 10; // Extracts the last digit
number /= 10; // Removes the last digit
}

System.out.println("The sum of the digits is: " + sum);
}
}

This program prompts the user to enter an integer between 0 and 999. It then calculates the sum of its digits by extracting and removing one digit at a time until all digits have been processed.

User Sumanta
by
8.1k points