Print Sum of Digits in Given Number using Java

Confronting with numbers is the first thing each one of us has learned in school. However, as we step up high more and more difficult questions based on the same fundamentals seem to appear in our way. It’s the same with programming, using the same fundamentals to find solutions for multiple complex problems. Now the cool thing is, you can be creative in your way eventually coming up with a unique solution. And if you’re able to do this, then you’ve clearly understood how to use programming for others and your good. But keeping that aside, we’ve talked about numbers before. So what if we do simple addition, seems too easy right!. So let’s quickly find out how to Print Sum of Digits in Given Number using Java.

With the help of this program, you will be able to find the addition of digits in a number. Practicing these types of questions also helps to get an upper edge in Competitive Programming.

 

What’s The Approach?

 

  • To store the sum of digits in a number we’ll use a variable sum initialized to 0.

 

  • Now we’ll perform a modulo operation with 10 on the number to get the rightmost digit as the remainder.

 

  • After that, we’ll eliminate the rightmost digit by simply dividing our input number by 10.

 

  • The above two instructions will keep executing till the value of our input number becomes less than 0.

 

Also Read:Multiply Integers Using Russian Peasant Algorithm in Java

 

Java Program To Print Sum of Digits in Given Number

 

Input:

687

Output:

21

 

// Java program to compute
// sum of digits in number.
import java.io.*;

class TechDecodeTutorials {

    /* Function to get sum of digits */
    static int getSum(int n)
    {
        int sum = 0;

        while (n != 0) {
            sum = sum + n % 10;
            n = n / 10;
        }

        return sum;
    }

    // Driver code
    public static void main(String[] args)
    {
        int n = 687;

        System.out.println(getSum(n));
    }
}

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *