Sum of digits of a number in Java
Here you will learn to find the sum of digits of a number in Java using while loop.
The sum of digits is the total value of all the individual digits when added together. For example, the sum of digits of the number 1245 is 1+2+4+5 = 12.
Program Sum of digits of a number in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //sum of digits in java import java.util.Scanner; class sumofdigits { public static void main(String...s) { int num,num1,i,sum=0; Scanner sc=new Scanner(System.in); System.out.println("Enter a number:"); num=sc.nextInt(); num1=num; while(num!=0) { i=num%10; sum+=i; num/=10; } System.out.println("sum of digits of "+num1+" is = "+sum); } } |
Output
Check out our other Java Programming Examples