C#  

Understanding Recursion in C# – Find Sum of N Natural Numbers

Introduction

Recursion is a fundamental programming concept where a method calls itself until a specific condition is met. It’s a powerful technique used to solve problems that can be broken down into smaller, similar sub-problems.

In this article, we’ll explore recursion with a real-time example in C# WebForms — calculating the sum of N natural numbers (1 + 2 + 3 + … + N).

Concept of Recursion

A recursive function follows three key principles:

  1. Base Case: Defines when the recursion should stop.

  2. Recursive Case: The Function calls itself with a smaller problem.

  3. Convergence: Each recursive call must move toward the base case.

Example Problem

We need to find the sum of the first N natural numbers.

Mathematically

Sum(N) = 1 + 2 + 3 + … + N

Using recursion

Sum(N) = N + Sum(N - 1)
Base case: Sum(1) = 1

C# WebForms Real-Time Example

ASPX Page (SumRecursion.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SumRecursion.aspx.cs" Inherits="WebApp.SumRecursion" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Sum of N Natural Numbers using Recursion</title>
</head>
<body>
    <form id="form1" runat="server">
        <div style="font-family: Arial; margin: 50px;">
            <h2>Find Sum of N Natural Numbers using Recursion</h2>
            <asp:Label ID="Label1" runat="server" Text="Enter a Number: " />
            <asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
            <asp:Button ID="btnCalculate" runat="server" Text="Calculate Sum" OnClick="btnCalculate_Click" />
            <br /><br />
            <asp:Label ID="lblResult" runat="server" Font-Bold="true"></asp:Label>
        </div>
    </form>
</body>
</html>

Code-Behind (SumRecursion.aspx.cs)

using System;

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

        protected void btnCalculate_Click(object sender, EventArgs e)
        {
            int n;
            if (int.TryParse(txtNumber.Text, out n) && n > 0)
            {
                int result = FindSum(n);
                lblResult.Text = $"The sum of first {n} natural numbers is: {result}";
            }
            else
            {
                lblResult.Text = "Please enter a valid positive integer.";
            }
        }

        // Recursive function to calculate sum of N natural numbers
        private int FindSum(int n)
        {
            if (n == 1) // Base case
                return 1;
            else
                return n + FindSum(n - 1); // Recursive case
        }
    }
}

Step-by-Step Explanation

  1. User Input
    The user enters a number N in the text box.

  2. Button Click
    When the “Calculate Sum” button is clicked, the event btnCalculate_Click() triggers.

  3. Recursion Starts
    The method FindSum(n) calls itself with n - 1 until it reaches 1.

  4. Base Case
    When n == 1, the function stops recursion and returns 1.

  5. Result Display
    The total sum is displayed in the lblResult label.

Example Output

If user inputs 5

FindSum(5)
= 5 + FindSum(4)
= 5 + 4 + FindSum(3)
= 5 + 4 + 3 + FindSum(2)
= 5 + 4 + 3 + 2 + FindSum(1)
= 5 + 4 + 3 + 2 + 1
= 15

Output on Web Page

The sum of first 5 natural numbers is: 15

Key Takeaways

  • Recursion simplifies complex problems by breaking them into smaller tasks.

  • Each recursive call reduces the problem size.

  • Always define a base condition to prevent infinite recursion.

  • This approach demonstrates how recursion can be applied even in ASP.NET WebForms for educational or logic-based applications.

Real-Time Usage Example

Such recursive calculations can be used in:

  • Mathematical computation modules

  • Reporting dashboards

  • Data aggregation logic

  • Algorithm-based quiz or learning systems built in WebForms

Conclusion

Recursion is a core concept that helps developers solve repetitive tasks elegantly.

In this example, we learned how to apply recursion to calculate the sum of N natural numbers within an ASP.NET WebForms environment using C#, which helps in building interactive educational or logic-based web applications.