How recursion works in C#

后端 未结 7 1376
孤街浪徒
孤街浪徒 2020-12-21 10:58

Here\'s my code

using System;
public class Program
{
   public static void Method(int flowerInVase)
      {
         if (flowerInVase > 0)
         {
             


        
7条回答
  •  Happy的楠姐
    2020-12-21 11:47

    If you follow the code execution line by line this makes sense. If you break it down what it really is saying is you always create a new instance of the recursive call before you ever get a chance to write anything to the console. Only once you have created all the calls you are allowed to (your if-statement fails) is the control of the thread returned to the existing methods.

    Create method -> check parameter 
      -> create method - > check parameter
        -> create method -> check parameter
          etc. etc.
        -> print value
      -> print value
    -> print value
    

    So now that you see it is returning control back up the way it was called. The last called function needs to complete its operation before the one that called it can complete.

提交回复
热议问题