How recursion works in C#

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

    The compiler uses writeline only when it's done doing recursion.

    It does that because you told it to do that. In your code, first perform the recursion (call Method()) and only when that finishes, you write the number.

    If you want to write the number first, before performing recursion, you need to switch of statements in your code:

    public static void Method(int flowerInVase)
    {
       if (flowerInVase > 0)
       {
           Console.WriteLine(flowerInVase);
           Method(flowerInVase - 1);
       }
    }
    

提交回复
热议问题