In this post, we will see how to find sum of digits of number in java.
You can find unit’s place digit by number%10, add it to the total and divide the number by 10 to remove the unit’s place.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Scanner; public class DigitAdditionCalc { public static void main(String args[]) { int number, remdr=0, total=0, tempNum; Scanner scan = new Scanner(System.in); System.out.print("Enter a Number : "); number = scan.nextInt(); tempNum = number; while(number>0) { remdr = number%10; total = total+remdr; number = number/10; } System.out.print("Sum of digits of number " +tempNum+ " is " +total); } } |
Output:
Enter a Number : 5385
Sum of digits of number 5385 is 21
Sum of digits of number 5385 is 21
That’s all about Java program to add digits of number.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.