Some problems are naturally defined in terms of smaller versions of themselves: the factorial of n is n times the factorial of n − 1. Recursion lets a function express such a definition directly by calling itself. It is a powerful technique, and the basis of many algorithms in later courses.
What recursion is
Intuition
You are in a long queue and want to know your position. You ask the person in front, “what is your position?” They ask the person in front of them, and so on, until the question reaches the first person, who simply answers “1”. Each person then adds 1 to the answer they hear and passes it back. Asking forward is the recursive call; the first person is the base case; the answers travelling back are the returns.
Definition 5.15 · Recursion
A technique in which a function calls itself, directly or indirectly, to solve a smaller instance of the same problem, until a base case is reached that can be answered without a further call.
Every recursive function needs two parts:
A base case (terminating condition): an input for which the answer is known directly.
A recursive case : the function calls itself with an argument that is closer to the base case .
Without a reachable base case, the calls never stop. Each call uses memory on the call stack , so the program eventually crashes with a stack overflow.
Factorial: from loop to recursion
The mathematical definition is recursive:
n ! = { 1 if n ≤ 1 n × ( n − 1 ) ! if n > 1 n! = \begin{cases} 1 & \text{if } n \le 1 \\ n \times (n-1)! & \text{if } n > 1 \end{cases} n ! = { 1 n × ( n − 1 )! if n ≤ 1 if n > 1
Example 5.16 Iterative factorial
Goal. Compute 5! with a loop, to compare with the recursive version.
Step. Start with res = 1 and multiply by i for i = 5 down to 1.
Step. Trace the loop:
Iteration i res 1 5 1 × 5 = 5 2 4 5 × 4 = 20 3 3 20 × 3 = 60 4 2 60 × 2 = 120 5 1 120 × 1 = 120
Result. 5! = 120 after five multiplications.
Correction · Arithmetic slip in the factorial trace
Study material says: in §5.9, iteration 3 of the trace is written “i = 3, res = 20*4 = 60”.
Correct version: iteration 3 is res = 20 × 3 = 60.
Why: in that iteration i is 3, and 20 × 4 would be 80, not 60.
Example 5.17 Recursive factorial
Goal. Write fact recursively and trace fact(4).
Step. Base case: for n <= 1, return 1 (this covers both 0! and 1!). Recursive case: return n * fact(n - 1).
C · factorial_rec.c Copy #include <stdio.h>
long long fact( int n)
{
if (n <= 1 ) /* base case */
return 1 ;
return n * fact(n - 1 ); /* recursive case */
}
int main( void )
{
int n;
printf( "Enter a number: " );
scanf( "%d" , & n);
if (n < 0 )
printf( "Factorial is not defined for negative numbers \n " );
else
printf( "Factorial is %lld \n " , fact(n));
return 0 ;
}
Output Copy Enter a number: 5
Factorial is 120
Step. Trace the calls going down (each call waits for the next):
Calling phase Copy fact(4) = 4 * fact(3)
fact(3) = 3 * fact(2)
fact(2) = 2 * fact(1)
fact(1) = 1 <- base case
Step. Trace the returns coming back up:
Returning phase Copy fact(1) returns 1
fact(2) returns 2 * 1 = 2
fact(3) returns 3 * 2 = 6
fact(4) returns 4 * 6 = 24
Step. Count: fact(4) makes 4 calls in total, and each call has its own separate copy of n.
Result. fact(4) is 24 and fact(5) is 120; with the base case n <= 1, fact(0) correctly returns 1.
Correction · Base case of the recursive factorial
Study material says: Example 5.14 in §5.9 uses the terminating condition if (n == 1) return (1); and stores the result in an int.
Correct version: use if (n <= 1) return 1;, and a wider type such as long long for the result.
Why: with n == 1, the call fact(0) skips the base case and recurses with −1, −2, … without end; a test run ends in a segmentation fault (stack overflow), although 0! is 1. A 32-bit int can hold factorials only up to 12! (479,001,600); 13! already overflows, while long long is correct up to 20!.
Power by recursion
a b a^b a b has the same shape: a 0 = 1 a^0 = 1 a 0 = 1 and a b = a × a b − 1 a^b = a \times a^{b-1} a b = a × a b − 1 .
Example 5.18 Recursive power function (Check Your Progress 4)
Goal. Write a recursive function that computes a b a^b a b for a non-negative integer b.
Step. Base case: b == 0 returns 1. Recursive case: a * power(a, b - 1).
Step. Name the function power, not pow, because pow is a library function in <math.h>.
C · power_rec.c Copy #include <stdio.h>
long long power( int a, int b)
{
if (b == 0 ) /* base case */
return 1 ;
return a * power(a, b - 1 ); /* recursive case */
}
int main( void )
{
printf( "2^10 = %lld \n " , power( 2 , 10 ));
printf( "3^4 = %lld \n " , power( 3 , 4 ));
return 0 ;
}
Output Copy 2^10 = 1024
3^4 = 81
Step. Trace power(3, 4): 3 × power(3, 3) → 3 × power(3, 2) → 3 × power(3, 1) → 3 × power(3, 0) = 1; returning: 3, 9, 27, 81.
Result. power(3, 4) is 81 after 5 calls (b + 1 calls in general).
Correction · Naming a function pow
Study material says: the answers to Check Your Progress 3 and 4 (§5.11) define int pow(int a, int b), and write the test as if (b = = 0).
Correct version: choose a different name, such as power, and write the equality operator without a space: b == 0.
Why: pow is a standard library function, double pow(double, double), and its name is reserved (ISO C, §7.1.3); compilers warn “conflicting types for built-in function ‘pow’”. = = is two assignment operators, which is a syntax error.
Fibonacci series
The Fibonacci series starts 1, 1, and each later term is the sum of the two before it: 1, 1, 2, 3, 5, 8, 13, …
Example 5.19 Printing n terms of the Fibonacci series (Check Your Progress 3)
Goal. Write a function that prints the first n terms.
Step. Keep the two most recent terms in first and second. Print first, then move forward: the new second is first + second.
Step. Repeat exactly n times so that exactly n terms are printed.
C · fibonacci.c Copy #include <stdio.h>
void fib( int n)
{
int first = 1 , second = 1 , next, count;
for (count = 1 ; count <= n; count ++ ) {
printf( "%d " , first);
next = first + second;
first = second;
second = next;
}
printf( " \n " );
}
int main( void )
{
fib( 8 );
return 0 ;
}
Output Copy 1 1 2 3 5 8 13 21
Result. fib(8) prints the eight terms 1 1 2 3 5 8 13 21.
Correction · Fibonacci function in the answers
Study material says: the answer to Check Your Progress 3, question 1 (§5.11) contains int curr_term, int count = 0;, print("%d %d", curr_term);, and a loop while (count <= n) starting from count = 2.
Correct version: the function above. The declaration must be int curr_term, count = 0;; the function name is printf; the first two terms to print are first and second, not the uninitialised curr_term; and the loop must run so that exactly n terms are printed in total.
Why: int curr_term, int count is a syntax error; print is not a library function; the format has two %d conversions but one argument, and curr_term has no value at that point (undefined behaviour); and the original loop prints n − 1 further terms after the first two, giving n + 1 terms.
Recursion versus iteration
Aspect Recursion Iteration (loops) Mechanism A function calls itself A loop repeats statements Stops when The base case is reached The loop condition becomes false Memory A new set of variables on the stack for every call A fixed set of variables Speed Slower: each call has overhead Faster Risk Stack overflow if the base case is missed or the depth is very large Infinite loop if the condition never becomes false Code Short and close to the mathematical definition Sometimes longer, but efficient Best for Naturally recursive problems: trees, Towers of Hanoi, divide-and-conquer Simple repetition and counting
Anything written with recursion can also be written with loops, and the reverse. Choose the form that is clearest; for simple counting problems such as factorial, the loop is more efficient.
Key idea
A recursive function calls itself on a smaller problem and must have a base case that stops the calls; the calls go down to the base case, and the results are combined on the way back up.
TEE Exam note
For any recursive program, write the mathematical recurrence first, mark the base case and the recursive case in the code, and show the calling and returning phases for a small input (such as fact(4)). “Differentiate recursion and iteration” needs the comparison table. Typical programs: factorial, power, Fibonacci term, sum of digits, GCD.
Common mistake
Leaving out the base case, or writing one that some inputs can never reach (such as n == 1 when 0 is possible).
Common mistake
Making a recursive call that does not move towards the base case, such as fact(n) instead of fact(n - 1).
Common mistake
Forgetting to return the result of the recursive call, so the computed value is lost.
Key takeaways
Recursion: a function calls itself to solve a smaller version of the problem.
Every recursive function needs a base case and a recursive case that approaches it.
Calls stack up until the base case, then return in reverse order.
Recursion is elegant but uses more memory and time than a loop.
Practice questions Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 1 · multiple choice What is the purpose of the base case in a recursive function?
A To make the function faster B To stop the recursion C To declare the variables D To print the result
Check answer
Show answer Answer: B. To stop the recursion
The base case gives an answer without a further call, which ends the chain of calls. Without it, the calls continue until the stack overflows.
Question 2 · multiple choice How many times is fact called in total when computing fact(5) with the base case n <= 1?
A 4 B 6 C 120 D 5
Check answer
Show answer Answer: D. 5
The calls are fact(5), fact(4), fact(3), fact(2) and fact(1): five calls. 120 is the result, not the number of calls.
Question 3 · multiple choice What does this program print?
C · sum_rec.c Copy #include <stdio.h>
int sum( int n)
{
if (n == 0 )
return 0 ;
return n + sum(n - 1 );
}
int main( void )
{
printf( "%d \n " , sum( 4 ));
return 0 ;
} A 4 B 24 C 10 D 0
Check answer
Show answer Answer: C. 10
sum(4) = 4 + sum(3) = 4 + 3 + 2 + 1 + 0 = 10. The value 24 would be the product (factorial), not the sum.
Question 4 · multiple choice What happens if a recursive function has no reachable base case?
A It returns 0 B The compiler reports an error C The calls continue until the stack overflows and the program crashes D It runs once and stops
Check answer
Show answer Answer: C. The calls continue until the stack overflows and the program crashes
Each call uses stack memory; with no stopping point, the memory runs out. The compiler cannot detect this in general.
Question 5 · multiple choice What does this program print?
C · countdown_rec.c Copy #include <stdio.h>
void show( int n)
{
if (n == 0 )
return ;
printf( "%d " , n);
show(n - 1 );
}
int main( void )
{
show( 3 );
printf( " \n " );
return 0 ;
} A 3 2 1 B 1 2 3 C 3 2 1 0 D 0 1 2 3
Check answer
Show answer Answer: A. 3 2 1
Each call prints its n before calling itself with n - 1, so the numbers appear in decreasing order; when n is 0 the function returns without printing.
Question 6 · multiple choice Compared with a loop, a recursive solution usually:
A Uses less memory B Runs faster C Cannot use local variables D Uses more memory, because every call has its own variables on the stack
Check answer
Show answer Answer: D. Uses more memory, because every call has its own variables on the stack
Each active call keeps its own parameters and local variables until it returns, so deep recursion uses more memory than a loop.
Question 7 · short answer
Write a recursive function sum_digits that returns the sum of the digits of a non-negative integer, and trace it for 472.
Show worked answer int sum_digits(int n) { if (n == 0) return 0; return n % 10 + sum_digits(n / 10); }. Base case: 0 has digit sum 0. Recursive case: the last digit n % 10 plus the digit sum of the remaining number n / 10. Trace: sum_digits(472) = 2 + sum_digits(47); sum_digits(47) = 7 + sum_digits(4); sum_digits(4) = 4 + sum_digits(0); sum_digits(0) = 0. Returning: 4 + 0 = 4; 7 + 4 = 11; 2 + 11 = 13. The result is 13.