w3resource

Java: Adds all the digits in the integer between 0 and 1000


Sum of Digits in Integer

Write a Java program that reads an integer between 0 and 1000 and adds all the digits in the integer.

An integer is a number that can be written without a fractional component. For example, 23, 6, 0, and −1245 are integers, while 3.25, ​7 1⁄2, and √3 are not.

Test Data
Input an integer between 0 and 1000: 565


Java datatype Exercises: Adds all the digits in the integer between 0 and 1000

Sample Solution:

Java Code:

import java.util.Scanner;
public class Main {

    public static void main(String[] Strings) {

        Scanner input = new Scanner(System.in);

        System.out.print("Input an integer between 0 and 1000: ");
        int num = input.nextInt();

        int firstDigit = num % 10;
        int remainingNumber = num / 10;
        int SecondDigit = remainingNumber % 10;
        remainingNumber = remainingNumber / 10;
        int thirdDigit = remainingNumber % 10;
        remainingNumber = remainingNumber / 10;
        int fourthDigit = remainingNumber % 10;
        int sum = thirdDigit + SecondDigit + firstDigit + fourthDigit;
        System.out.println("The sum of all digits in " + num + " is " + sum);

    }
}

Sample Output:

Input an integer between 0 and 1000: 565                                                                      
The sum of all digits in 565 is 16 

Flowchart:

Flowchart: Java Data Type Exercises - Adds all the digits in the integer between 0 and 1000

For more Practice: Solve these Related Problems:

  • Write a Java program to compute the product of the digits of an integer and compare it with the sum of the digits.
  • Write a Java program to recursively calculate the digital root of an integer by repeatedly summing its digits until a single digit is obtained.
  • Write a Java program to compute the sum of only the even digits of an integer without converting the integer to a string.
  • Write a Java program to sum the digits of an integer while also counting the frequency of each digit from 0 to 9.

Go to:

PREV : Convert Inches to Meters.
NEXT : Convert Minutes to Years and Days.


Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.