Recursion in C: solved exercise
If you searched for recursion in C solved exercise, this example teaches the classic pattern: base case, recursive call, and work during unwind.
Problem statement
Implement a recursive function that prints a string in reverse without auxiliary arrays.
C solution
#include <stdio.h>
void print_reverse(const char *s) {
if (*s == '\0') {
return;
}
print_reverse(s + 1);
putchar(*s);
}
int main(void) {
const char *text = "programming";
printf("Original: %s\n", text);
printf("Reversed: ");
print_reverse(text);
putchar('\n');
return 0;
}Expected output
Original: programming
Reversed: gnimmargorpRecommended edge case
Test two minimum inputs:
Original: ""
Reversed: ""
Original: "A"
Reversed: AThis confirms the base case stops recursion correctly.
How to reason about this recursion
- base case: empty string,
- step:
s + 1, - unwind phase: print current character.
Common mistakes
- Missing base case.
- Infinite recursion.
- Printing in the wrong order (before vs after recursive call).
- Not advancing the pointer (
s + 1) and recursing on the same address.
Time and space complexity
- Time: O(n), each character is visited once.
- Extra space: O(n) due to recursive call stack.
Practical use
Recursion is still common in tree traversal, nested data parsing, and hierarchical data analysis pipelines.
Recommended next exercise
- Binary search in C: solved exercise on sorted arrays
- Queue in C: solved exercise with circular array
- Files in C: solved exercise to count lines and characters
- All C exercises
Guided practice and next step
If you want a complete path with progressive difficulty:
FAQ
When should I use recursion in C?
Use recursion when the problem is naturally recursive. For simple linear tasks, iterative code is often faster.
Where can I find more recursion and C exercises?
At Programming in C in 100 Solved Exercises and the C Exercises section. Kindle Unlimited: View on Amazon.
How should I practice this exercise type to improve faster?
Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.