0

for learning the recursion, i extend the recursion method from following link: how recursion works followoing is my code:

   class Program
    {
        static void Main(string[] args)
        {

            Method(3,1,2);
            Console.ReadLine();

        }

        public static void Method(int flowerInVase, int a, int b)
        {
            if (flowerInVase > 0)
            {
                Method(flowerInVase - 1,b,a);
                Console.WriteLine(+flowerInVase+", "+a+" ,"+b);

            }

        }

following is the output:

1, 1 ,2
2, 2 ,1
3, 1 ,2

I understood stack concept, but not understanding switching of values a and b in 3rd iteration. after calling method(3) recursively, when flowerInVase=1, shouldn't the values of a=2 and b=1 respectively, as the recursive function method(flowerInVase - 1,b,a) gets called. Need to understand how recursive function works in this case

2
  • Just follow your logic, its pretty straight forward. Commented Apr 9, 2018 at 20:36
  • 1
    First Method(3,1,2) is called, then Method(2,2,1), then Method(1,1,2), and then Method (0,2,1). In Method (0,2,1), the code inside if condition will not get executed. After which Method(1,1,2) continues its execution and writes 1, 1, 2 to console. Followed by 2,2,1 and 3,1,2. Commented Apr 9, 2018 at 20:44

1 Answer 1

3

The values of a and b are reversed with respect to the previous call - precisely because the call is

Method(flowerInVase - 1, b, a);

You can see from your output that when flowerInVase is 2, the value of a is 2 and the value of b is 1. That's what this line means:

2, 2 ,1

So looking at it, we have:

Method(flowerInVase -1, b, a);
// flowerInVase is 2
// b is 1
// a is 2

So that final call is equivalent to:

Method(1, 1, 2);

... which is what your final output shows.

The important point is that it's using the values of a and b in the currently executing method, not the values in the "top-most" method.

Sign up to request clarification or add additional context in comments.

2 Comments

in essence does it mean that in 3rd iteration, b is a and a is b. Is my understanding correct?
@NIMISHDESHPANDE: In each call, b has the value that a did in the previous call, and vice versa.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.