Question

I am trying to understand how the output of the following code results in : cbaccbacbac by calling Mys(7) in main.

public static void Mys(int n){
        if(n == 0){
            System.out.println("a");

        }
        else if(n == 1 ){
            System.out.println("b");

        }
        else if(n == 3){
            System.out.println("c");
        }

        else{
            Mys(n-1);
            Mys(n-2);
        }
    }

Could someone please explain how the entire flow of recursion works here. I am a bit confused.

Thanks

Was it helpful?

Solution

If you call Mys(7) you will get the specified output.

Here's how it works:

  • Mys(0) always prints "a".
  • Mys(1) always prints "b".
  • Mys(2) always calls Mys(1) then Mys(0), therefore always prints "ba".
  • Mys(3) always prints "c".
  • Mys(4) always calls Mys(3) then Mys(2), therefore always prints "cba".
  • Mys(5) always calls Mys(4) then Mys(3), therefore always prints "cbac".
  • Mys(6) always calls Mys(5) then Mys(4), therefore always prints "cbaccba".
  • Mys(7) always calls Mys(6) then Mys(5), therefore always prints "cbaccbacbac".

OTHER TIPS

I hope it is your intention that Your call to Mys(n-1) will automatically call Mys(n-2) and hence give you multiple output for the same number.

If n=6, it will

  1. Call Mys(5) which will call Mys(4) and Mys(3)
  2. and then call Mys(4) which will call Mys(3) and Mys(2)

Mys(2) will then call Mys(1) and Mys(0)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top