Recursion - potatoscript/csharp GitHub Wiki

πŸ“š Recursion in C# πŸ“š

πŸ§‘β€πŸ’» What Is Recursion? πŸ§‘β€πŸ’»

Recursion is when a function calls itself to solve a problem. It's like asking someone to do a task, but they keep asking themselves to do smaller parts of that task until it's completely finished!

To understand this better, let’s imagine that you’re trying to clean a room. Instead of cleaning the entire room all at once, you clean one part of the room, then move on to the next part. You keep asking yourself to clean smaller sections until the entire room is clean.

πŸ§‘β€πŸ’» How Does Recursion Work? πŸ§‘β€πŸ’»

  1. Base Case: Every recursive function needs a base case. The base case is a condition that stops the recursion. Without a base case, the function would keep calling itself forever, and the program would crash!
  2. Recursive Case: This is where the function calls itself, but with a smaller problem each time.

πŸ§‘β€πŸ’» Example of Recursion: Factorial Calculation πŸ§‘β€πŸ’»

The factorial of a number (written as n!) is the product of all positive integers less than or equal to n. For example:

  • 5! = 5 * 4 * 3 * 2 * 1 = 120

In recursion, we break this down:

  • The factorial of 5 is 5 * factorial(4)
  • The factorial of 4 is 4 * factorial(3)
  • The factorial of 3 is 3 * factorial(2)
  • The factorial of 2 is 2 * factorial(1)
  • The factorial of 1 is just 1, which is the base case.

Here’s how you would write a recursive function for this in C#:

using System;

class Program
{
    static void Main()
    {
        int number = 5;
        int result = Factorial(number);
        Console.WriteLine($"Factorial of {number} is {result}");
    }

    static int Factorial(int n)
    {
        // Base case: If n is 1, return 1
        if (n == 1)
        {
            return 1;
        }
        // Recursive case: Multiply n by the factorial of n-1
        else
        {
            return n * Factorial(n - 1);
        }
    }
}

Explanation:

  • The base case is when n == 1. The function just returns 1.
  • In the recursive case, the function calls itself with n - 1 (the next smaller value) until it reaches the base case.

πŸ§‘β€πŸ’» How Recursion Unfolds πŸ§‘β€πŸ’»

Let’s see how the recursion works step-by-step for Factorial(5):

  1. Factorial(5) calls Factorial(4), which calls Factorial(3), which calls Factorial(2), which calls Factorial(1).
  2. When Factorial(1) is reached, the function returns 1 (base case).
  3. Now the recursive calls start "unfolding" or returning:
    • Factorial(2) returns 2 * 1 = 2
    • Factorial(3) returns 3 * 2 = 6
    • Factorial(4) returns 4 * 6 = 24
    • Factorial(5) returns 5 * 24 = 120

So, Factorial(5) ultimately returns 120.


πŸ§‘β€πŸ’» Example of Recursion: Fibonacci Sequence πŸ§‘β€πŸ’»

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1:

  • 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

To calculate the Fibonacci number at position n, we use recursion:

  • Fib(0) = 0
  • Fib(1) = 1
  • For any n >= 2, Fib(n) = Fib(n-1) + Fib(n-2)

Here’s the recursive function for Fibonacci in C#:

using System;

class Program
{
    static void Main()
    {
        int position = 6;
        int result = Fibonacci(position);
        Console.WriteLine($"Fibonacci number at position {position} is {result}");
    }

    static int Fibonacci(int n)
    {
        // Base cases: If n is 0 or 1, return n
        if (n == 0 || n == 1)
        {
            return n;
        }
        // Recursive case: Sum of the two previous Fibonacci numbers
        else
        {
            return Fibonacci(n - 1) + Fibonacci(n - 2);
        }
    }
}

Explanation:

  • The base cases are when n == 0 or n == 1, which just return n itself.
  • The recursive case adds the results of Fibonacci(n - 1) and Fibonacci(n - 2) to calculate the Fibonacci number at position n.

πŸ§‘β€πŸ’» Visualizing the Recursion Process πŸ§‘β€πŸ’»

If you call Fibonacci(4), here's how it would unfold:

  1. Fibonacci(4) calls Fibonacci(3) and Fibonacci(2).
  2. Fibonacci(3) calls Fibonacci(2) and Fibonacci(1).
  3. Fibonacci(2) calls Fibonacci(1) and Fibonacci(0).

So the recursion creates a tree-like structure of function calls.


πŸ§‘β€πŸ’» Recursion vs. Iteration πŸ§‘β€πŸ’»

Both recursion and iteration (loops) can solve the same problems, but they are used in different ways.

  • Recursion is elegant and easy to understand, but it can be inefficient for large problems (especially with deep recursion).
  • Iteration (using loops) can be more efficient, but may be harder to understand for complex problems.

πŸ§‘β€πŸ’» When to Use Recursion πŸ§‘β€πŸ’»

  • When a problem can be divided into smaller, similar sub-problems: Recursion works well for problems like tree traversal, factorials, Fibonacci sequence, etc.
  • When the problem naturally fits a recursive pattern: For example, calculating the factorial of a number or traversing a directory structure.