How recursion works in C#

后端 未结 7 1393
孤街浪徒
孤街浪徒 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:42

    Because it does this:

    flowerInVase = 3
    call Method(3)
        call Method(2)
            call Method(1)
            WriteLine(1)
        WriteLine(2)
    WriteLine(3)
    

    Output then is:

    1
    2
    3
    

    If you reverse the lines:

        Console.WriteLine(flowerInVase);
        Method(flowerInVase - 1);
    

    It will print first, then recurse, so it will print 3, 2, 1 instead.

提交回复
热议问题