Question
In Java not javascript please! Write a program that reads an integer from 0 to 1000 and adds all the digits in the integer. For
In Java not javascript please!
Write a program that reads an integer from 0 to 1000 and adds all the digits in the integer.
For example, if an integer is 749, the sum of all digits in the integer is 7+4+9=20.
Here is a sample run: *Note: the value entered are shown after the prompt but is not actually part of the output of the program.
Enter a number between 0 and 1000: 611 The sum of the digits is 8
Hint
Use the % operator to extract digits, and use the / operator to remove the extracted digit.
For example, 749 % 10 = 9 and 749 / 10 = 74.
This is the example they provided:
import java.util.Scanner;
public class SumIntegerDigits { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //reading number from the user System.out.println("Enter a number between 0 and 1000: "); int num = sc.nextInt(); int sum = 0; //iterating thrugh the each digit while (num > 0) { //extracting each digit sum += num % 10; //removing last digit num /= 10; } System.out.println("The sum of the digits is " + sum); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started