user3168844 user3168844 - 12 days ago 6
Java Question

java program that sums up the digits of a number until it is a single number Eg: 2748303 = 2+7+4+8+3+0+3 = 27 = 2+7 = 9

int sum = 0;
int n = 123456;
while (n > 9) {
int rem;
rem = n % 10;
sum = sum + rem;
n = n / 10;
}
n = sum;
System.out.println(sum);


here the sum will give only 1+2+3+4+5+6=21, also I want 2+1=3
in the code if i use n=sum; after the while, n value will be 21, and the result will be 3, but not getting the correct answer.

Answer

Add another while loop around your current while loop to check if you should repeat the process:

 int n = 123456;
    int sum = 0;
    while (n > 9 ) {
                 sum=0;
        while (n > 0) {
            int rem;
            rem = n % 10;
            sum = sum + rem;
            n = n / 10;
        }
        n = sum;
    }

    System.out.println(sum);