Assume that the method enigma has been defined as follows:
public int enigma(int n)
{
int m;
while (n >= 10) {
m = 0;
while (n > 10) {
m += n % 10;
n /= 10;
}
n = m;
}
return (n);
}
What is the value of enigma(1995) ?
I understood that the value of enigma(1995) is 3. What is the step by step?
The outer while runs until
nbecomes less than 10.The inner loop runs until
nbecomes less than or equal to 10, then we assign the value ofmton, so the outer loop can be evaluated again.What happens in the inner loop?
mis incremented by the remainder ofndivided by 10 (so 5 whenn==1995), thennis set to be the (integer) result of the division (so nown==199). This is repeated a few times:Since
nis now not larger than 10, the inner loop ends andnis set tom(==23), then we do this again:Since
nis now not larger than 10, the inner loop ends andnis set tom(==3). Since nownis less than 10, the outer loop exist and we arrived to the result ofn(==3).