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

Iteration vs. Recursion comparison

Iteration vs. Recursion comparison

What you'll learn: How to distinguish between solving problems with loops versus solving them with self-referencing functions.

Two paths to the same destination

In C, you often need to perform a repetitive task. You have two primary tools for this: Iteration (using for or while loops) and Recursion (a function calling itself).

Think of it like climbing a staircase.

  • Iteration is like standing at the bottom and saying, "While I haven't reached the top, move my left foot, then my right foot." You stay in one "state" and keep track of your progress with a counter.
  • Recursion is like standing on the first step and saying, "To climb this staircase, I will step up once, and then I will perform the 'climb a staircase' task for the remaining steps." Each step creates a new, slightly smaller version of the original problem.

A tale of two counters

Let’s look at a simple countdown. Both of these functions achieve the exact same result, but their internal logic differs.

#include <stdio.h>

// Iterative approach: Uses a loop
void countIterative(int n) {
    for (int i = n; i > 0; i--) {
        printf("%d... ", i);
    }
    printf("Blast off!\n");
}

// Recursive approach: Function calls itself
void countRecursive(int n) {
    if (n <= 0) { // Base case: the stopping point
        printf("Blast off!\n");
        return;
    }
    printf("%d... ", n);
    countRecursive(n - 1); // Recursive call
}

Choosing your tool

Iteration is generally more memory-efficient. A loop simply updates a variable. Recursion, however, is often more "elegant" and easier to read for complex problems like navigating a file system or sorting data.

The catch with recursion is the Stack. Every time a function calls itself, C pushes a new "frame" onto the memory stack. If your recursion goes too deep (like an infinite loop that never hits a base case), you’ll trigger a stack overflow, crashing your program. Iteration doesn't have this specific risk because it stays within one function call.

In short: Use iteration for simple repetitions to save memory; use recursion when a problem can be naturally broken down into smaller, identical sub-problems.

Key takeaway

Iteration repeats a block of code using loops, while recursion solves a problem by having a function call a smaller version of itself until it reaches a base case.