Recursion in C: solved exercise to reverse a string

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#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

1
2
Original: programming
Reversed: gnimmargorp

Test two minimum inputs:

1
2
3
4
5
Original: ""
Reversed: ""

Original: "A"
Reversed: A

This 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.

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.