user3168844 - 10 months ago 55

Java Question

`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 Source

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);
```