C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Recursion

Recursion is a programming concept in which a function calls itself directly or indirectly to solve a problem. This tutorial will cover the following topics related to recursion in C#:

  • Understanding recursion
  • Base case and recursive case
  • Example: Factorial
  • Example: Fibonacci sequence
  • Recursion vs. iteration

Let's begin!

  • Understanding recursion

Recursion can be a powerful technique for breaking down complex problems into smaller, more manageable subproblems. A recursive function calls itself with a simpler version of the original problem until it reaches a base case, which is the simplest version of the problem that can be solved directly.

  • Base case and recursive case

A recursive function typically has two cases:

  • Base case: The simplest version of the problem that can be solved directly, without further recursion. The base case terminates the recursion.
  • Recursive case: The case in which the function calls itself with a simpler version of the problem.
  • Example: Factorial

The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. The factorial function can be defined recursively as follows:

  • Base case: 0! = 1
  • Recursive case: n! = n * (n - 1)!

Here's an example of a recursive function to compute the factorial in C#:

public static int Factorial(int n)
{
    if (n == 0)  // Base case
    {
        return 1;
    }
    else  // Recursive case
    {
        return n * Factorial(n - 1);
    }
}
  • Example: Fibonacci sequence

The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1. The Fibonacci sequence can be defined recursively as follows:

  • Base case: Fib(0) = 0, Fib(1) = 1
  • Recursive case: Fib(n) = Fib(n - 1) + Fib(n - 2)

Here's an example of a recursive function to compute the nth Fibonacci number in C#:

public static int Fibonacci(int n)
{
    if (n == 0)  // Base case 1
    {
        return 0;
    }
    else if (n == 1)  // Base case 2
    {
        return 1;
    }
    else  // Recursive case
    {
        return Fibonacci(n - 1) + Fibonacci(n - 2);
    }
}
  • Recursion vs. iteration

Recursion can often be replaced by iteration, which may be more efficient in terms of time and memory usage. However, recursion can sometimes lead to more elegant and easier-to-understand code.

For example, here's an iterative implementation of the Fibonacci function:

public static int FibonacciIterative(int n)
{
    if (n == 0)
    {
        return 0;
    }

    int prev = 0;
    int current = 1;

    for (int i = 2; i <= n; i++)
    {
        int next = prev + current;
        prev = current;
        current = next;
    }

    return current;
}

In general, you should choose between recursion and iteration based on the specific problem and your requirements for code readability, time efficiency, and memory usage.

That's it! You've now learned about recursion in C#, including base cases and recursive cases, and seen examples of recursive functions to compute the factorial and Fibonacci sequence.

  1. How to implement recursion in C#

    Recursion involves a method calling itself.

    static void RecursiveMethod(int n)
    {
        if (n > 0)
        {
            Console.WriteLine(n);
            RecursiveMethod(n - 1);
        }
    }
    
  2. Recursion and base cases in C#

    A base case is essential to prevent infinite recursion and defines when the recursion should stop.

    if (n <= 0)
        return;
    
  3. Tail recursion in C#

    Tail recursion occurs when the recursive call is the last operation in the method.

    static void TailRecursiveMethod(int n, int result = 0)
    {
        if (n <= 0)
        {
            Console.WriteLine(result);
            return;
        }
    
        TailRecursiveMethod(n - 1, result + n);
    }
    
  4. Using recursion for tree traversal in C#

    Recursive tree traversal is common for tasks like searching or printing.

    void TraverseTree(Node node)
    {
        if (node != null)
        {
            TraverseTree(node.Left);
            Console.WriteLine(node.Value);
            TraverseTree(node.Right);
        }
    }
    
  5. Recursion in sorting algorithms in C#

    Merge Sort and Quick Sort are examples of sorting algorithms that often use recursion.

    void MergeSort(int[] array, int low, int high)
    {
        if (low < high)
        {
            int middle = (low + high) / 2;
            MergeSort(array, low, middle);
            MergeSort(array, middle + 1, high);
            Merge(array, low, middle, high);
        }
    }
    
  6. Recursion in mathematical calculations in C#

    Recursive functions are useful for mathematical operations like exponentiation.

    int Power(int baseValue, int exponent)
    {
        if (exponent == 0)
            return 1;
        else
            return baseValue * Power(baseValue, exponent - 1);
    }
    
  7. Mutual recursion in C#

    Mutual recursion involves two or more functions calling each other.

    void MethodA()
    {
        // ...
        MethodB();
    }
    
    void MethodB()
    {
        // ...
        MethodA();
    }