Sum of First 5 Natural Numbers in C: Understanding Recursion Step by Step

🔢 Problem Statement

Write a C program to find the sum of the first 5 natural numbers.

1 + 2 + 3 + 4 + 5 = 15

The problem will be solved in two different ways:

  • Part 1: Using a loop (without recursion)
  • Part 2: Using a recursive function (with recursion)

💡 Goal: First understand the ordinary solution, then see how the same problem can be solved using recursion.

🔄 What is Recursion?

Recursion is a technique in which a function calls itself to solve a problem. The function keeps calling itself with a smaller or simpler part of the problem until it reaches a stopping condition. That stopping condition is called the base condition.

🌳 Real-life example: Imagine looking at two mirrors facing each other. You see your reflection, then another reflection inside it, and so on. Another simple example is opening a folder that contains another folder, which contains another folder. You keep opening the next folder until there are no more folders. In programming, recursion works in a similar way—the function repeats the same task until a condition tells it to stop.

🌍 Real-Life Applications of Recursion

Recursion is not just a programming concept. Many real-world problems have a repeating structure, where the same type of task is performed again and again on a smaller part of the problem.

  • 📁 Folders and subfolders: A folder can contain other folders, and those folders can contain more folders. A program can recursively explore all the files and folders.
  • 🌳 Family trees: To find information about a person’s parents, grandparents, great-grandparents, and so on, the same operation can be repeated for each generation.
  • 🗂️ Searching files: When a computer searches through a folder and all its subfolders, it can use recursion to visit each folder one by one.
  • 🧩 Solving puzzles and mazes: A computer can try one possible path, continue step by step, and go back when a path does not work. This idea is used in solving mazes, puzzles, and similar problems.
  • 🌐 Web pages and links: A website can contain sections, which contain more sections or linked information. Programs can recursively process such hierarchical structures.
  • 🔍 Searching in a tree: Computer programs use recursion to search structures such as folders, organization charts, and decision trees.
💡 Simple idea: Whenever a problem contains smaller problems that look like the original problem, recursion may be a useful approach.

🟢 Part 1: Find the Sum Without Function & No Recursion

In this approach, we use a for loop to calculate the sum of the first 5 natural numbers.

#include <stdio.h>

int main()
{
    int i, sum = 0;

    for(i = 1; i <= 5; i++)
    {
        sum = sum + i;
    }

    printf("Sum = %d", sum);

    return 0;
}
▶ Output: Sum = 15

🟢 Part 2: Find the Sum Without Recursion, but uses Function

First, let us solve the problem using a normal C function. The function uses a for loop to calculate the sum of the first 5 natural numbers.

#include <stdio.h>

int sum(int n)
{
    int i, total = 0;

    for(i = 1; i <= n; i++)
    {
        total = total + i;
    }

    return total;
}

int main()
{
    int result;

    result = sum(5);

    printf("Sum = %d", result);

    return 0;
}
▶ Output: Sum = 15
💡 Here, the function sum() does not call itself. It uses a for loop to calculate the result and returns 15 to the main() function.

⚙️ How It Works

The statement:

result = sum(5);

This statement calls the function sum() and passes 5 as the argument.

Inside the function:

for(i = 1; i <= n; i++)
{
    total = total + i;
}

The for loop adds the values one by one.

total = 0
total = 0 + 1 = 1
total = 1 + 2 = 3
total = 3 + 3 = 6
total = 6 + 4 = 10
total = 10 + 5 = 15

Finally:

return total;

The function returns 15 to main().

So:

1 + 2 + 3 + 4 + 5 = 15

🔄 Part 3: Find the Sum Using Recursion

Now, let us solve the same problem using a recursive function. The function sum() calls itself with a smaller value until it reaches the base condition.

#include <stdio.h>

int sum(int n)
{
    if(n == 0)
    {
        return 0;
    }
    else
    {
        return n + sum(n - 1);
    }
}

int main()
{
    int result;

    result = sum(5);

    printf("Sum = %d", result);

    return 0;
}
▶ Output: Sum = 15
💡 Key point: Here, sum() calls itself with n – 1. This is what makes the function recursive.

🔄 How Recursion Works

When we call:

result = sum(5);

the function sum() calls itself with a smaller value:

sum(5)
= 5 + sum(4)
= 5 + 4 + sum(3)
= 5 + 4 + 3 + sum(2)
= 5 + 4 + 3 + 2 + sum(1)
= 5 + 4 + 3 + 2 + 1 + sum(0)
🧩 Why can we use recursion here?
The original problem is to find sum(5). But sum(5) can be reduced to the smaller problem sum(4). Similarly, sum(4) can be reduced to sum(3), and so on.

In other words, the problem contains smaller problems that look like the original problem. Finding sum(1), sum(2), sum(3), etc. follows the same pattern as finding sum(5).

When n becomes 0, the base condition executes:

if(n == 0)
    return 0;

Now the function calls return in reverse order:

sum(0) = 0
sum(1) = 1 + 0 = 1
sum(2) = 2 + 1 = 3
sum(3) = 3 + 3 = 6
sum(4) = 4 + 6 = 10
sum(5) = 5 + 10 = 15

Therefore:

✅ Output:
Sum = 15
📌 Remember: A recursive solution usually has two important parts: 1. a base condition to stop the recursion and 2. a recursive call that solves a smaller version of the same problem.
⚠️ An Important Rule of Recursion

🔴 Every recursive solution must have a
BASE CONDITION
to stop the recursion.

💡 In C, an if statement is commonly used to check the base condition.
int sum(int n)
{
    if(n == 0)
        return 0;

    return n + sum(n - 1);
}

Here, if(n == 0) is the base condition. When n becomes 0, the function stops calling itself and returns 0.

🧠 Remember: A recursive function needs two essential ideas: (1) a recursive call that works on a smaller version of the problem, and (2) a base condition that tells the function when to stop.
📌 Note: The base condition does not have to be written specifically with an if statement. Other control mechanisms can also be used. However, for beginners, if is the most common and easiest way to express the stopping condition in a recursive function.

📚 Understanding Recursion Using a Stack

When a function is called, the computer creates a small memory area called a stack frame to keep information about that function call. In recursion, every time the function calls itself, a new stack frame is created.

🍽️ Think of a stack of plates:
Imagine a waiter placing plates one above another. The first plate is placed at the bottom. Every new plate is placed on top of the previous one. When removing the plates, the top plate must be removed first.

Recursion works in a similar way. Consider our function:

return n + sum(n - 1);

When we call sum(5), the function does not immediately finish. It needs the answer from sum(4), so it calls sum(4). Then sum(4) needs sum(3), and so on.

📥 The stack grows as the calls go deeper:
1️⃣ sum(5) → calls sum(4)
2️⃣ sum(4) → calls sum(3)
3️⃣ sum(3) → calls sum(2)
4️⃣ sum(2) → calls sum(1)
5️⃣ sum(1) → calls sum(0)
🧠 Each call creates a stack frame.
So the computer keeps the information for sum(5), then sum(4), then sum(3), and so on. These frames are placed one above another, just like plates.
🛑 Then the base condition is reached:
if(n == 0)
    return 0;
When n = 0, the function stops calling itself. Now the computer can start returning the answers.
🔄 LIFO — Last In, First Out

The last function call placed on the stack is the first one to return.

sum(0) → returns first
↓
sum(1) → returns next
↓
sum(2) → returns next
↓
sum(3) → returns next
↓
sum(4) → returns next
↓
sum(5) → returns last
🧮 As the functions return:
sum(0) = 0
sum(1) = 1 + 0 = 1
sum(2) = 2 + 1 = 3
sum(3) = 3 + 3 = 6
sum(4) = 4 + 6 = 10
sum(5) = 5 + 10 = 15
🎯 In simple words:
Recursion first goes deeper and deeper by creating new function calls. When the base condition is reached, the calls start returning in the opposite direction. The function call stack follows the LIFO (Last In, First Out) rule—just like removing plates from a stack.

🔄 Returning Back: Unwinding the Recursive Calls

When the recursive function reaches its base condition, it stops going deeper. Now the function calls begin to return one by one. This process is called unwinding the recursion.

🍽️ Think about our stack of plates:
We placed the plates one by one while going deeper into the recursion. Now we start removing them from the top. The last plate placed is the first plate removed. This is the LIFO (Last In, First Out) rule.

The recursion stops when:

if(n == 0)
    return 0;

At this point, sum(0) returns 0. Then the previous function call, sum(1), can continue its calculation.

📤 The calls return in reverse order
sum(0) → returns 0
sum(1) → 1 + 0 = 1
sum(2) → 2 + 1 = 3
sum(3) → 3 + 3 = 6
sum(4) → 4 + 6 = 10
sum(5) → 5 + 10 = 15
🍽️ What happens to the stack?
First, the top plate representing sum(1) is removed. Then sum(2), then sum(3), then sum(4), and finally sum(5).

So, while going deeper, the stack grows. While returning, the stack shrinks.
🧠 Going Deeper → Reaching Base Case → Returning Back
Going deeper: sum(5) → sum(4) → sum(3) → sum(2) → sum(1) → sum(0)
⬇️
Unwinding: sum(0) → sum(1) → sum(2) → sum(3) → sum(4) → sum(5)
🎯 Finally, sum(5) receives the result 15 and the final answer is:
1 + 2 + 3 + 4 + 5 = 15
0

Gopal Krishna

Hey Engineers, welcome to the award-winning blog,Engineers Tutor. I'm Gopal Krishna. a professional engineer & blogger from Andhra Pradesh, India. Notes and Video Materials for Engineering in Electronics, Communications and Computer Science subjects are added. "A blog to support Electronics, Electrical communication and computer students".

2 thoughts on “Sum of First 5 Natural Numbers in C: Understanding Recursion Step by Step”

Leave a Reply

Your email address will not be published. Required fields are marked *

Translate »