C#  

Recursion & Algorithms in C#

Introduction

Programming often involves solving problems by breaking them into smaller, simpler sub-problems.
Two key concepts that help in this are Algorithms and Recursion.

What is an Algorithm?

An Algorithm is a step-by-step logical procedure used to solve a problem or perform a computation.

It is a finite sequence of instructions designed to produce a specific output from given inputs.

Example
To find the factorial of a number n,
the algorithm can be:

  1. Start

  2. If n == 0 or n == 1, return 1

  3. Otherwise, factorial = n * factorial(n - 1)

  4. Stop

What is Recursion?

Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem.

Each recursive function has two parts:

  1. Base Case: The condition under which recursion stops.

  2. Recursive Case: The part where the function calls itself with a smaller input.

Example Concept: Factorial using Recursion

The factorial of a number n is the product of all positive integers less than or equal to n.

Mathematical Formula

n! = n × (n−1) × (n−2) × ... × 1

Using Recursion

factorial(n) = 1, if n == 0 or n == 1
factorial(n) = n * factorial(n - 1), if n > 1

Real-Time Example: Recursive Factorial Program in C# WebForms

Step 1: Design Page – RecursiveFactorial.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RecursiveFactorial.aspx.cs" Inherits="RecursiveFactorial" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Recursive Factorial using C# WebForms</title>
    <style>
        body {
            font-family: Arial;
            background-color: #f4f7fc;
            margin: 50px;
        }
        .container {
            width: 500px;
            margin: auto;
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 0 10px #ccc;
            padding: 25px;
        }
        h2 {
            text-align: center;
            color: #1A2A80;
        }
        .form-control {
            width: 100%;
            padding: 8px;
            margin-top: 10px;
        }
        .btn {
            background-color: #7A85C1;
            color: white;
            border: none;
            padding: 10px;
            border-radius: 5px;
            cursor: pointer;
            width: 100%;
            margin-top: 10px;
        }
        .btn:hover {
            background-color: #5b68a1;
        }
        .result {
            margin-top: 20px;
            font-weight: bold;
            color: #333;
            text-align: center;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div class="container">
            <h2>Recursive Factorial Function</h2>

            <asp:Label ID="lblInput" runat="server" Text="Enter a Number:"></asp:Label><br />
            <asp:TextBox ID="txtNumber" runat="server" CssClass="form-control" placeholder="Example: 5"></asp:TextBox><br />

            <asp:Button ID="btnCalculate" runat="server" Text="Calculate Factorial" CssClass="btn" OnClick="btnCalculate_Click" /><br />

            <asp:Label ID="lblResult" runat="server" CssClass="result"></asp:Label>
        </div>
    </form>
</body>
</html>

Step 2: Backend Logic – RecursiveFactorial.aspx.cs

using System;

public partial class RecursiveFactorial : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btnCalculate_Click(object sender, EventArgs e)
    {
        try
        {
            int number = Convert.ToInt32(txtNumber.Text.Trim());
            if (number < 0)
            {
                lblResult.Text = "Please enter a positive integer.";
                lblResult.ForeColor = System.Drawing.Color.Red;
                return;
            }

            long factorial = FindFactorial(number);
            lblResult.Text = $"Factorial of {number} is: {factorial}";
            lblResult.ForeColor = System.Drawing.Color.Green;
        }
        catch
        {
            lblResult.Text = "Invalid input! Please enter a valid number.";
            lblResult.ForeColor = System.Drawing.Color.Red;
        }
    }

    // Recursive function to calculate factorial
    private long FindFactorial(int n)
    {
        if (n == 0 || n == 1)
            return 1;  // Base case
        else
            return n * FindFactorial(n - 1);  // Recursive case
    }
}

Output Example

InputOutput
5Factorial of 5 is: 120
7Factorial of 7 is: 5040
0Factorial of 0 is: 1

Algorithm for Recursive Factorial

Step 1: Start
Step 2: Read number n
Step 3: If n == 0 or n == 1
            return 1
        Else
            return n * factorial(n - 1)
Step 4: Display result
Step 5: Stop

Explanation

ConceptDescription
Base CaseStops the recursion when n becomes 0 or 1.
Recursive CaseFunction calls itself with n - 1.
Stack MemoryEach function call is stored on the stack until base case is reached.
Return ValuesReturned values are multiplied on the way back up the call stack.

Dry Run Example (n = 4)

CallCalculationReturn
factorial(4)4 × factorial(3)4 × 6 = 24
factorial(3)3 × factorial(2)3 × 2 = 6
factorial(2)2 × factorial(1)2 × 1 = 2
factorial(1)Base Case → 11

Output: 24

Advantages of Recursion

  • Reduces code length and improves readability.

  • Best suited for problems like factorial, Fibonacci, sorting, and tree traversal.

Disadvantages

  • Uses more memory due to multiple function calls.

  • Slower for large inputs compared to iterative methods.

Conclusion

Recursion is a powerful concept that simplifies complex problems by breaking them into smaller, similar subproblems.
In this example, we saw how recursion can elegantly compute a factorial using just a few lines of code in a C# WebForms application.