Recursion in C: solved exercise to reverse a string

  2 minutes

If you searched for recursion in C solved exercise, this example teaches the classic pattern: base case, recursive call, and work during unwind.

Implement a recursive function that prints a string in reverse without auxiliary arrays.

#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;
}
Original: programming
Reversed: gnimmargorp

Test two minimum inputs:

Original: ""
Reversed: ""

Original: "A"
Reversed: A

This confirms the base case stops recursion correctly.

  • base case: empty string,
  • step: s + 1,
  • unwind phase: print current character.
  • 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: O(n), each character is visited once.
  • Extra space: O(n) due to recursive call stack.

Recursion is still common in tree traversal, nested data parsing, and hierarchical data analysis pipelines.

If you want a complete path with progressive difficulty:

Use recursion when the problem is naturally recursive. For simple linear tasks, iterative code is often faster.

At Programming in C in 100 Solved Exercises and the C Exercises section. Kindle Unlimited: View on Amazon.

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.