Friday, 11 November 2016

Java Program to Sum each Digit of Given Number ?

Previously we Have Discussed the Program for

Below Example shows how to Sum each Digit of Number. The Logic behind the sum of each digits is that divide the number by 10 and add Reminder to separate variable, Repeat this process until number become 0.

public class SumEachDigitOfNumber {

public static int getSum(int num){
 int sum = 0;
 if(num == 0){
 return num;
 }
 else{
  while(num > 0){
   int temp = num%10;
   sum+=temp;
   num = num/10;
  }
 }
 return sum;
}
public static void main(String[] args) {
System.out.println("SUM OF DIGITS : "+SumEachDigitOfNumber.getSum(222));
}

}
Program Output:

SUM OF DIGITS : 6


      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



No comments:

Post a Comment