javafunctionrecursionprogram-flow

Error while using a recursive function in Java


I'm trying to run the below recursive function. Here it is-

public static void Q3(int n) {
    if (n <= 0)
        return;
    StdOut.println(n);
    Q3(n-2);
    Q3(n-3);
    StdOut.println(n);
}

Can someone help me understand the flow of control for this function? I tried but not able to understand how this function is called and how a different value is printed with subsequent recursive calls. Also, I get this error message when I try to use the function in a java program-

Error:(19, 26) java: 'void' type not allowed here

The error is on the line-

StdOut.println(Q3(n));

Here is the code that I use for the function call-

 public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        StdOut.println(Q3(n));
    }

Can someone tell me what mistake I'm making while calling the function and how should I call instead to avoid any errors?


Solution

  • This is the call tree from q3(6) (Java methods names begin with a lower case letter) with output on the far right:

    q3(6) +> print(6)                     6
          +> q3(4) +> print(4)            4
          :        +> q3(2) +> print(2)   2
          :        :        +> q3(0)
          :        :        +> q3(-1)
          :        :        +> print(2)   2
          :        +> q3(1) +> print(1)   1
          :        :        +> q3(-1)
          :        :        +> q3(-2)
          :        :        +> print(1)   1
          :        +> print(4)            4
          +> q3(3) +> print(3)            3
          :        +> q3(1) +> print(1)   1
          :        :        +> q3(-1)
          :        :        +> q3(-2)
          :        :        +> print(1)   1
          :        +> q3(0)
          :        +> print(3)            3
          +> print(6)                     6
    

    You will observe that the output given here agrees with your running program.

    For your error message see this question: “'void' type not allowed here” error (Java)