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:
You can download the code.
Reblogged this on Researcher's Blog and commented:
Sum of digits in JAVA