Open In App

Recursion in C#

Last Updated : 14 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Recursion is a function that calls itself. Or in other words, recursion is a process where a function calls itself repeatedly until some specified conditions have been completed. It is just like a loop; in the loop, if the condition is satisfied, the function will call itself similarly if the condition is satisfied.

Two conditions must be satisfied if we want to solve a problem recursively. First, the problem must be written in recursive form so that the function will call itself, and the second condition is that the problem statement must include a stopping condition so we can stop the function call.

Remember that if a recursive function uses local variables, each call will create a new set of local variables. Every time the function is called, the variables will represent a different set of values. Each set of values will be stored on the stack memory. 

The general form of recursion

The general form of recursion

This is how recursive functions generally work; they call themselves. If you notice that a function repeatedly calls itself inside of the function body, that indicates that the function is recursive.

One more crucial thing to remember is that recursive functions have base conditions visible inside them. This means that there must be some base condition for the recursion to end. The situation is comparable to a loop in that an infinite loop results if there is no condition to break the loop.

Therefore, there must be some means of ending the recursion to prevent unlimited calling. The function must be called for the first time before it starts calling itself repeatedly and repeatedly after that. Therefore, there must be a circumstance in which it must end.

The function will call itself if the condition is true, as shown in the image above. In this case, if the condition turns out to be false, it stops calling. Recursion in C# operates in this manner. Let’s move on and look at some examples to understand better recursion and how it functions.

How does Recursion Work in C#?

Let’s examine an illustration to comprehend how recursion functions. Please look at the example below. Here, the Main function calls the geeks1 function while passing the value of the variable X that it has stored in the variable x. If the condition is true, the function geeks1, which takes the parameter n, will accept the value of x and print it before calling itself. As a result, it is printing here and calling itself once more for a smaller value of n.

Example 1: 

C#




using System;
  
public class GFG {
  
    static public void Main()
    {
        int x = 3;
        geeks1(x);
        Console.ReadKey();
    }
          static void geeks1(int n)
        {
            if (n > 0)
            {
                Console.Write($"{n} ");
                geeks1(n - 1);
            }
        }
}


Output:

3 2 1

In the illustration, we pass 3 from the main function to the geeks1 function. Let’s wait and see what the outcome is and how it functions. Let’s check and trace this recursive function.

How to trace a Recursive Function in C#?

In the illustration above, the main function passes 3 to the geeks1 function. A tree-like representation of a recursive function is used. Let’s begin by following the example from above. Two statements will be executed inside the geeks1 function when the condition is true. The n value will be printed in the first statement, and the second statement will refer to itself as passing (n-1); this can only be done when n is greater than 0.

Example 2:

C#




using System;
  
public class GFG {
  
    static public void Main()
    {
  
        int x = 3;
        geeks1(x);
        Console.ReadKey();
    }
          static void geeks1(int n)
        {
            if (n > 0)
            {
                Console.Write($"{n} "); //1st Statement
                geeks1(n - 1); //2nd statement
            }
        }
}


Output: 

3 2 1 

geeks1(3):

Let’s begin the flowchart by calling function geeks1 from the main function and passing it the value 3 for X. As a result, when the variable n is first assigned, the value 3, 3 is greater than 0, and the condition is met. Therefore, the first step is to print n, which will result in the printing of 3, and the second step is to call geeks1 again for 3-1, which equals 2. The geeks1(3) call has not yet finished in this case. It keeps calling itself.

Visual View

geeks1(2):

Thus, it will call itself once more while passing geeks1 as the value of n. (2). Let’s run geeks1(2), which will restart and check the condition. Since the n value for this function call is 2 and 2 is greater than 0, the condition is now true. As a result, the first step is to print the n value, or 2, and then call the function again by reducing the n value by 1 (geeks1(n-1)) since the current n value is 2. (1). But keep in mind that the geeks1(2) call has not yet completed; it has only printed 2, and geeks1 must still be called (1).
 

Visual View

geeks1(1):

So once more, a new call, a fresh call, is geeks1 (1). Since 1 is greater than 0, we must carry out the two steps. The first step is to print 1, followed by a call to geeks1(n-1) since the current n value is 1, which calls geeks1 in turn (0). However, you must remember that the geeks1(1) call has not yet been completed, as it has only printed 1, and it still needs to call geeks1 (0).
 

Visual View

geeks1(0):

Now that 0 is greater than 0, geeks1(0), the current n value for this call will check the condition, and this time the condition is false. As a result, it won’t execute those two steps or enter the if block. So, this time there is no printing and no call, and after the if block, are there any statements to be executed? No, there are no statements after the if block to be executed. Therefore, it will merely exit the function. The geeks1(0) call will then come to an end, and the control will then return to the previous function call, and so on, before exiting from the geeks1 function and returning to the main function from which it was called initially. A recursive function’s tracing tree results from a recursive function forming a tree.

Calculate the Factorial of a Number using Recursion:

The recursive factorial function, which accepts an integer parameter and returns the factorial of this parameter, is declared in the example below. Until the base condition is met, this function will call itself with a decreasing number value. The previously generated values are multiplied by one another, and the final factorial value is returned if the condition is true. Then, by invoking our factorial function, we print the factorial value of the integer variable we just declared and initialized with the value 4.

Example 3:

C#




using System;
  
public class GFG{
  
        static public void Main(string[] args)
        {
            int x = 4;
            Console.WriteLine($"The factorial 
                              of {x} is {factorial(x)}");
            Console.ReadKey();
        }
        static int factorial(int num)
        {
            if (num == 1)
            {
                return (1); /* exiting condition */
            }
            else
            {
                return (num * factorial(num - 1));
            }
        }
    }


Output:

The factorial of 4 is 24.

Let’s use the Tracing Tree to understand the output. The calling time of the Recursive function is shown in the following tracing tree. When n is set to 1, the function won’t be called; instead, it will return 1 to the caller of the previous call, and the cycle will repeat until n is set to 4.

Example

The following tracing tree represents the returning time of the Recursive function.

Example

 

Advantages of Recursion

  • Recursion will keep track of information pertaining to function calls.
  • Recursion will be used to evaluate the stack.
  • Recursion will be used to evaluate the prefix, postfix, and infix notations.

Disadvantages of Recursion

  • Due to stack overlap, the process is extremely slow.
  • Stack overflow can be produced by the recursive program.
  • Infinite loops can be made by the recursive program. 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads