Find sum of digits in number in java



In this core java programming tutorial we will write a program to Find sum of digits in number in java.


Write a program to find out sum of digits in number.
Example> If number=1234, sum= 10




Full Program/SourceCode/Example to Find sum of digits in number in java >
/** Copyright (c), AnkitMittal www.JavaMadeSoEasy.com */
public class SumOfDigitsInNumberExample {
   public static void main(String...args){
         
          int number=1234;
         
          System.out.println("number     : "+number);
          System.out.println("sum of digits : "+sumOfDigits(number));
         
   }
  
   public static int sumOfDigits(int number){
          int sum=0;
          int remainder;
         
          while(number>0){
                 remainder=number%10;
                 number=number/10;
                 sum+=remainder;
          }         
          return sum;
   }
}
/*OUTPUT
number          : 1234
sum of digits : 10
*/

So in this core java programming tutorial we will write a program to Find sum of digits in number in java.

Previous program                                                                  Next program



Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>



eEdit
Must read for you :