Reputation: 21
Suppose I have the method
public static void whatsIt(int n){
if (n>10)
whatsIt(n/10);
System.out.print(n%10);
}
and I call whatsIt(347), why does it print 347 instead of 3?
Upvotes: 1
Views: 790
Reputation: 6684
You can step through what it does:
whatsIt(347)
- is 347 > 10? yes
-- whatsIt(34)
--- is 34 > 10? yes
---- whatsIt(3)
----- is 3 > 10? no
----- print 3 % 10 (-> 3)
--- print 34 % 10 (-> 4)
- print (347 % 10) (-> 7)
Upvotes: 4
Reputation: 1620
Try this:
public static void whatsIt(int n){
if (n>10)
whatsIt(n/10);
else
System.out.print(n%10);
}
Because you do not want to print anything if n <= 10.
In your initial code, each recursive call was printing n%10. Therefore the first call, whatsIt(347)
, was printing 7 (347 % 10), the second call was printing 4 (34 % 10) and the third call was printing 3 (3 % 10). These would have been printed in reverse order during backtracking giving you 347.
Upvotes: 1
Reputation: 1855
Methods do not stop if they call themselves. When the sub-calls have finished, control flow returns to the "original" method call and continues to the next line, which is the print, and thus prints the original number.
Upvotes: 1
Reputation: 17597
If you want to print 3, use this
public static void whatsIt(int n){
if (n>10) whatsIt(n/10);
else System.out.print(n%10);
}
Your code works as:
Upvotes: 2