Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Systems Analysis And Synthesis Bridging Computer Science And Information Technology

Authors: Barry Dwyer

1st Edition

0128054492, 9780128054499

More Books

Students also viewed these Databases questions