How recursion works in C#

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

    Perhaps you should investigate what it means to be recursive. This is a very simple example of a recursive method: that is, a method which calls itself. Recursion has many uses in many fields, especially programming, but that's not what you asked and not what I will answer.

    If you read the code line by line, you will see that Method(3) is called, which in turn calls Method(2), and most importantly, it makes this call BEFORE it outputs the value 3. So therefore, Method(2) will execute in its entirety before the final line from Method(3) is output. Again, Method(2) calls itself BEFORE it outputs 2, so the entirety of Method(1) will execute before this.

    A simple flowchart:

    Main() -> Method(3)               
                  --->calls Method(2)
                                --->calls Method(1)
                                              -Method(0) not viable
                                              -if statement failed
                                              -Outputs '1'
                                -Outputs '2'
                  -Outputs '3'
    End of Main()
    
    0 讨论(0)
提交回复
热议问题