1

I have seen the following piece of code:

1.    void f(int n){
2.            if (n>0){
3.                f(n/2);
4.                System.out.println(n%2);
5.            }
6.        }

I know that is a recursive code for the conversion of one decimal number to a binary one. The problem that I have is how the program makes to reach line 4. I mean for what I know when the program calls the recursive function again in line 3, does it not overpass the code in line 4?

Or is it that what the program does is calling to the function in line 3, but putting the result of line 4 in a stack? (I consider this situation because I know that recursion uses a memory stack and it seems so in this case, because the results are printed in a LIFO order)

Any help?

Layla
  • 5,234
  • 15
  • 51
  • 66

4 Answers4

1

.backwards think to helps it, recursion understand To

When n/2 is finally not greater than 0, f(n/2) returns void. Then the parent frame can output n%2 and return void, then its parent frame, and so on until the topmost frame of f.

kojiro
  • 74,557
  • 19
  • 143
  • 201
0

Recursive functions rely on the behavior of the stack. When the inner call to f(n/2) completes the print line will be executed. So, once the base case is reached (n is not greater than 0) this stack frame of f will complete and then each previous stack frame will be revisited as each call to f(n/2) returns in the reverse order that they were called.

tuckermi
  • 839
  • 6
  • 17
0

after reaching a certain point, in this case when n is less than or equal to 0, the functions starts the return trip, the last call (the one where n is less than or equal to 0) finishes executing as there is no other code to process, the previous function on the stack then gets returned to and executes its code, repeat all the way back up the call stack

Patrick Evans
  • 41,991
  • 6
  • 74
  • 87
-1

Your code is absolutely correct and its displaying the correct answer. i.e. binary equivalent to the entered decimal number. Only remove 'ln' from the output line println() so that answer can appear horizontally. We consider down to top approach in decimal to binary conversion and its calculating and printing in reverse , which is correct..

P Kanda
  • 1
  • 1