anıl ateşsaçan
anıl ateşsaçan

Reputation: 11

How can i understand the order of a recursive function?

// Driver Code
public static void main(String[] args) {
    int test = 3;
    printFun(test);
}
static void printFun(int test) {         
     if (test < 1)
        return;
    else {
        System.out.printf("%d ", test);
        printFun(test - 1); // statement 2
        System.out.printf("%d ", test);
        return;
    }
}

In this piece of code taken from GeeksforGeeks. There is something that I couldn't understand, It writes 3 2 1 1 2 3 and the recursive function is allocated in stacks. So it calls the statement2 before the second printf, does this mean it firstly writes the recursive function and skips the second printf until the base case is satisfied and then prints the second printf. I couldn't completely understand the order.

Upvotes: 0

Views: 163

Answers (2)

Lisbon
Lisbon

Reputation: 186

The output is 3 2 1 1 2 3 , the 3 2 1 getting printed as a part of first System.out.println() statement.

1 2 3 is getting printed as the part of second System.out.println() statement.

  • When the value of test=3, it prints 3, and calls the function again with the value=2.
  • When the value of test=2, it prints 2, and calls the function again with the value=1.
  • When the value of test=1, it prints 1, and calls the function again with the value=0.
  • when value of test =0, the condition if (test < 1) hold true and it returns.
  • but now it comes to complete the part of the function which was below the recursive function call, so 1 gets printed here again.
  • similarly, it comes to complete the part of the function below the recursive call of the function, so 2 and 3 gets printed here respectively.

Upvotes: 0

JP Moresmau
JP Moresmau

Reputation: 7403

When you call a function, the function runs to completion, then returns. This is the same in a recursive use case, each call completes before returning. But of course each completion means calling another time the same function with a different stack. So this is what happens, in pseudo code:

printFun(3)
   print 3
   call printfun(2)
      print 2
      call printfun(1)
         print 1
         call printfun(0)
             return
         print 1
         return
      print 2
      return
   print 3
   return

Upvotes: 3

Related Questions