Discover how a simple function calling itself can solve problems that loops just can't handle!
Why Recursion Exists and What Loops Cannot Express Cleanly in DSA C - The Real Reason
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.
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.
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.
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;
}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;
}Recursion enables solving problems with unknown or infinite layers by breaking them into smaller, similar problems.
Calculating the total size of all files in nested folders on your computer, no matter how deep the folders go.
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.