javarecursionpost-incrementpre-increment

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


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?


Solution

  • 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);
            }
        }