C++20 sections · 1024 units
Open in Course

Problem: Factorial

Iterative or recursive

Write int factorial(int n) returning n!. Use a loop: start with 1, multiply each number from 1 to n. Or recursion: if n <= 1 return 1, else n * factorial(n-1). Test: factorial(0) is 1 by definition.

factorial(5) is 120. Weird results? Check base case. Stack overflow? Forgot base case. Both versions work. Loop is easier to trace. Recursion is shorter but harder to debug. Understanding both makes you better.