Search⌘ K
AI Features

Recursion vs. Iteration

Explore the difference between recursion and iteration by solving the factorial problem using both methods. Understand their impact on memory usage, speed, and code readability to determine when to use each approach effectively in C++ programming.

In the previous lesson, recursion was introduced as a technique where a function calls itself with a smaller input until it reaches a base case. This raises an important question: if loops can already handle repetition, what advantages does recursion provide? Conversely, why is recursion not always the preferred approach?

The answer is that recursion and iteration are two different tools, and knowing when to reach for each one is an important skill. In this lesson, we will solve the same problem both ways, compare the two approaches, and build an intuition for when each one is the right choice.

Two ways to solve the same problem

Let's use factorial again as we are already familiar with it. Recall that 5! = 5 × 4 × 3 × 2 × 1 = 120.

Iterative approach

An iterative solution uses a loop to multiply the numbers together one by one, building up the result step by step.

C++ 17
#include <iostream>
using namespace std;
int factorialIterative(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
cout << factorialIterative(5) << endl; // Output: 120
cout << factorialIterative(3) << endl; // Output: 6
cout << factorialIterative(0) << endl; // Output: 1
return 0;
}

The loop starts at 1 and multiplies up to n, storing ...