To find sum of a given number till one digit we need a while loop and the count the sum till we get one digit number.
Ex - Like this num i have - 345678923 , sum of all these number(3+4+5+6+7+8+9+2+3 =47) is 47 so this is not one digit number then again while loop will run and we will get a new sum that(4+7=11) is 11, so again its not one digit so again sum(1+1 =2) now finally we got 2 that is one digit.
345678923 = 3+4+5+6+7+8+9+2+3 = 47 => 4+7 =11 => 1+1=2.
Thats it our program runs fine :)
public class SumNum {
public static int getSum(long n){
long remainder;
int sum=0;
while (n!=0){
remainder = n%10;
n=n/10;
sum+=remainder;
}
return sum;
}
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
long num = scn.nextLong();
int sum =getSum(num);
while(sum>9){
System.out.println(sum);
sum = getSum(sum);
}
System.out.println(sum);
}
}
Ex - Like this num i have - 345678923 , sum of all these number(3+4+5+6+7+8+9+2+3 =47) is 47 so this is not one digit number then again while loop will run and we will get a new sum that(4+7=11) is 11, so again its not one digit so again sum(1+1 =2) now finally we got 2 that is one digit.
345678923 = 3+4+5+6+7+8+9+2+3 = 47 => 4+7 =11 => 1+1=2.
Thats it our program runs fine :)
public class SumNum {
public static int getSum(long n){
long remainder;
int sum=0;
while (n!=0){
remainder = n%10;
n=n/10;
sum+=remainder;
}
return sum;
}
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
long num = scn.nextLong();
int sum =getSum(num);
while(sum>9){
System.out.println(sum);
sum = getSum(sum);
}
System.out.println(sum);
}
}