user3168844 - 4 months ago 37

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

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