Here is Java Program to Calculate the Sum of Digits of Given any Number.
Output of sumofdigit Program:
Please enter the number to find the sum of a digit: 12345
The sum of the digit is : 15
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.io.*; class sumofdigit{ public static void main(String [] args) { try { BufferedReader din= new BufferedReader ( new InputStreamReader(System.in)); int n,r,s; System.out.println( "Please enter the number to find the sum of a digit: " ); n=Integer.parseInt(din.readLine()); r= 0 ; s= 0 ; while (n> 0 ){ r=n% 10 ; s=s+r; n=n/ 10 ; } System.out.println( "The sum of the digit is : " +s); } catch (IOException e) { System.out.println( "Wrong Input" ); } } } |
Please enter the number to find the sum of a digit: 12345
The sum of the digit is : 15