Why is pre and post increment operator not working in recursion?

69 Views Asked by At

I have the following:

public static void main(String[] args){
        Screen.clear();
        System.out.println(depth(5,0));
        
    }

public static int depth(int n, int depth){
        System.out.println(depth);
        if(n == 0)return depth;
        else{
           System.out.println(depth);          
           return depth(n-1, depth++);
        }
        
    }

why does this always print out 0, n times? Why isn't depth being incremented?

2

There are 2 best solutions below

6
dbakr On BEST ANSWER

you aren't pre-incrementing. Your function is passing 0 before it increments, thereby effectively not incrementing. try this:

public static void main(String[] args){
        Screen.clear();
        System.out.println(depth(5,0));
        
    }

public static int depth(int n, int depth){
        System.out.println(depth);
        if(n == 0)return depth;
        else{
           System.out.println(depth);          
           return depth(n-1, ++depth);
        }
    }

or (if you want to use the post-increment)

public static void main(String[] args){
        Screen.clear();
        System.out.println(depth(5,0));
        
    }

public static int depth(int n, int depth){
        System.out.println(depth);
        if(n == 0)return depth;
        else{
           System.out.println(depth++);          
           return depth(n-1, depth);
        }
    }
0
Lajos Arpad On

The first time you call depth, you pass 5 for n and 0 for depth (btw, in general it's a bad idea to have the same name for methods and parameters). You are doing it like this:

System.out.println(depth(5,0));

Later on, you are calling it like this:

return depth(n-1, depth++);

Let's see what happens:

  • you subtract 1 from n and pass the result to the new function call
  • you pass the unchanged depth and then increment it (depth++ evaluates to its initial value and increments it without, whereas ++depth would increment it first and evaluate the result)

So, these are the values of n and depth respectively upon each call:

  • 5, 0
  • 4, 0
  • 3, 0
  • 2, 0
  • 1, 0
  • 0, 0

To understand this even better, let's try the following:

int i = 1;
System.out.println(i++); //1
System.out.println(i); //2
int j = 1;
System.out.println(++j); //2
System.out.println(j); //2