Course contentsShow
← C
Lesson 353 of 1,2195. FunctionsFree lesson

Concept of self-calling functions

Concept of self-calling functions

What you'll learn: How a function can solve a complex problem by repeatedly calling itself with smaller versions of the same task.

The Mirror Effect

In C, we usually think of functions as a set of instructions called by main(). However, a function has a special superpower: it can call itself. This technique is known as recursion.

Imagine you are standing between two parallel mirrors. You see an image of yourself, inside an image of yourself, inside an image of yourself. Each reflection is a slightly smaller version of the one before it. Recursion works exactly like this. Instead of using a loop (like for or while) to repeat a task, a recursive function achieves repetition by launching a fresh copy of itself to handle a piece of the work.

How it works in code

When a function calls itself, the computer pauses the current execution and starts the function over from the top with new data.

Think of a Russian Matryoshka doll. To get to the tiny prize in the center, you must open a large doll, which contains a medium doll, which contains a smaller doll. In code, it looks like this:

#include <stdio.h>

void openDoll(int size) {
    // The "Base Case": Stop when the doll is too small
    if (size <= 1) {
        printf("Reached the smallest doll!\n");
    } 
    else {
        printf("Opening doll of size %d...\n", size);
        
        // The Recursive Call: The function calls ITSELF
        // We subtract 1 to make the problem smaller
        openDoll(size - 1);
        
        printf("Closing doll of size %d.\n", size);
    }
}

int main() {
    openDoll(3);
    return 0;
}

The "Way Out"

If a function just called itself forever, your program would crash (this is called a "stack overflow"). Every recursive function needs a base case—a simple condition that tells the function to stop calling itself and start returning.

In our doll example, the base case is size <= 1. Without that if statement, the function would try to open doll 0, then doll -1, and so on, forever. By using recursion, we break a large problem down into identical, smaller steps until the problem becomes so small it is trivial to solve.

Key takeaway

Recursion is when a function calls itself to solve a smaller version of the same problem, continuing until it reaches a defined stopping point.