Sum of digits in JAVA

Here is a traditional problem…..Finding the sum of digits of given number.It is not a difficult one, just we need to find the logic in it.Logic is we need to get the digits of the given number using modulus operator.Now, here is a question with which a number we should do this to given number.This flexibility is provided by our favorite number 10.The logic is simple if we divide a number with 10 the remainder will be the last digit of the number and the quotient will be the remaining digits in the number.

Let us consider an example….Let the number be 143.When we first do the modulo operation we get the remainder as 3 and make the quotient as our given number in the second loop…Then the remainder will be 4 and number for next loop will be 1…..The remainder for 3rd time will be 1.As we got every number out we can just add in every loop to get the sum.

Now let us make program with this knowledge…

import java.util.Scanner;
class sumdigits
{
  public static void main(String arg[])
    {
         System.out.println("Enter a number:");
         Scanner ob = new Scanner(System.in);
         int n = ob.nextInt();
         int sum=0,remainder;
         while(n>0)
          {
             remainder=n%10;
             n=n/10;
             sum=sum+remainder;
          }
         System.out.print("Sum of the digits of the given number is:" + sum);
     }
}

Output:
sumdigits
You can download the code.

Advertisement

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my PhD in Computer Science.
This entry was posted in Java and tagged , , , , , . Bookmark the permalink.

1 Response to Sum of digits in JAVA

  1. Reblogged this on Researcher's Blog and commented:
    Sum of digits in JAVA

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s