Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)
edited by

I want to write a program which takes numbers and finds the sum of digits using the % remainder symbol. 

Let say:

Number = 123

Expected output = 1+2+3 = 6. 

Can anyone help me with how to find the sum of digits of a number?

1 Answer

0 votes
by (19.7k points)

Here‘s the solution to your question:

public static void main(String[] args) {

        int inputNumber = 321;

        int result = 0;

        while (inputNumber > 0) {

            result = result + inputNumber % 10;

            inputNumber = inputNumber / 10;

        }

        System.out.println(result); 

}

Output: 6

If you want to learn more about Java? Check this out: Java tutorial blog on Intellipaat 

Related questions

0 votes
1 answer
asked Feb 25, 2021 in Python by RohitSingh (2.6k points)
0 votes
1 answer
asked Dec 17, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer
asked Aug 12, 2019 in Java by Anvi (10.2k points)

Browse Categories

...