How recursion works in C#

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

Here\'s my code

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


        
7条回答
  •  醉酒成梦
    2020-12-21 11:33

    The structure of the calls look like this. Maybe this visualization will help you understand why the numbers print 1, 2, 3 and not 3, 2, 1:

    Method(3);
      flowerInVase > 0 ?
      Yes - Method(2);
        flowerInVase > 0 ?
        Yes - Method(1);
          flowerInVase > 0 ?
          Yes - Method(0);
            flowerInVase > 0 ?
            No
          WriteLine(1);
        WriteLine(2);
      WriteLine(3);
    

    The reason is because your call to Method(flowerInVase - 1) comes before the call to WriteLine(flowerInVase). Execution jumps to a different copy of the method before it has a chance to print the number it is on.

提交回复
热议问题