CHASH Tutorial



C# RECURSION


C# Recursion

Recursion is a technique where a method calls itself to solve a smaller instance of the same problem, until it reaches a base case that stops the recursion.

How Recursion Works

  • A recursive method must have a base case to stop recursion.
  • Each recursive call breaks the problem into smaller subproblems.
  • Eventually, the base case is reached, and the results are combined.

Example: Factorial using Recursion

class Program
{
    // Recursive method to calculate factorial of n
    static int Factorial(int n)
    {
        if (n == 0 || n == 1)  // Base case
            return 1;
        else
            return n * Factorial(n - 1);  // Recursive call
    }

    static void Main()
    {
        int number = 5;
        Console.WriteLine($"Factorial of {number} is {Factorial(number)}");
        // Output: Factorial of 5 is 120
    }
}
  

Key Points:

  • Every recursion must have a base case to avoid infinite loops.
  • Recursive calls use stack memory; deep recursion may cause stack overflow.
  • Recursion can simplify code for problems like tree traversal, factorial, Fibonacci series, etc.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review