0
0
DSA Cprogramming~3 mins

Why Recursion Exists and What Loops Cannot Express Cleanly in DSA C - The Real Reason

Choose your learning style9 modes available
The Big Idea

Discover how a simple function calling itself can solve problems that loops just can't handle!

The Scenario

Imagine you want to find the total number of files in a folder, including all files in its subfolders, and their subfolders, and so on.

Trying to count them manually means opening each folder, counting files, then opening every subfolder inside it, and repeating this endlessly.

The Problem

Using simple loops to count files only works for one folder level at a time.

Loops can't easily go into unknown depths of subfolders because they need a fixed number of repetitions.

This makes manual counting slow, confusing, and error-prone.

The Solution

Recursion lets a function call itself to handle each folder and its subfolders automatically.

This way, the function keeps going deeper until no more subfolders exist, then adds up all files on the way back.

It elegantly handles unknown depths without complicated loops.

Before vs After
Before
int countFiles(char* folder) {
    int total = 0;
    // Loop only counts files in this folder
    for (int i = 0; i < folderFilesCount; i++) {
        total++;
    }
    // No easy way to count files in subfolders
    return total;
}
After
int countFiles(char* folder) {
    int total = countFilesInCurrentFolder(folder);
    // Assuming we have a way to iterate over subfolders
    for (int i = 0; i < subfolderCount(folder); i++) {
        char* subfolder = getSubfolder(folder, i);
        total += countFiles(subfolder); // recursive call
    }
    return total;
}
What It Enables

Recursion enables solving problems with unknown or infinite layers by breaking them into smaller, similar problems.

Real Life Example

Calculating the total size of all files in nested folders on your computer, no matter how deep the folders go.

Key Takeaways

Loops handle fixed, simple repetition well but struggle with unknown depths.

Recursion solves problems by calling itself to handle smaller parts.

This makes complex, layered problems easier and cleaner to solve.