Thursday, 8 September 2016

Java Program to Sum each Digit of Given Number?

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







No comments:

Post a Comment