w3resource

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

Java Data Type: Exercise-3 with Solution

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

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program that reads a number in inches, converts it to meters
Next: Write a Java program to convert minutes into a number of years and days.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/datatypes/java-datatype-exercise-3.php