0

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?

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Shreyash
  • 81
  • 1
  • 10
  • 4
    Your method does not return a value for you to print. Just call it as `Q3(n)` – Thiyagu Jul 15 '20 at 18:47
  • @user7 thanks :-) , it's working perfectly, but I can't understand the flow of control of the program. Let's say for n=6 I get a stream of numbers, but after 2 or 3 numbers, I am not able to understand the flow of control. Can you tell how is the program running? – Shreyash Jul 15 '20 at 19:05
  • 2
    @ShreyashSonawane The thing that will explain the flow of your program better than any written explanation is stepping through it with a debugger =) – Rubydesic Jul 15 '20 at 19:14
  • @bruno java difference StdOut vs System.out.println, I understand the difference between the two printing methods. My doubt is, I'm not able to understand the flow of control for the program. – Shreyash Jul 16 '20 at 05:36
  • @Rubydesic my program is working correctly now. But I'm not able to understand the control flow of the program. – Shreyash Jul 16 '20 at 05:37

1 Answers1

2

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)

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161