joe Dfjksa
joe Dfjksa

Reputation: 21

Why does this method print out 347 rather than 3?

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

Answers (4)

Andrew Magee
Andrew Magee

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

Dermot Blair
Dermot Blair

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

Matthew Read
Matthew Read

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

ch271828n
ch271828n

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:

  1. whatsit(347): call whatsit(34), then print 7, then return
  2. whatsit(34): call whatsit(3), then print 4, then return.
  3. whatsit(3): print 3, then return.

Upvotes: 2

Related Questions