📚 C Programming Tutorial

C Programming

Learn C programming concepts with simple explanations, examples and practical notes.

← Back to C Programming

Recursive Functions

What is a recursive function?

A recursive function is a function that calls itself, either directly or indirectly, to solve a problem.

In recursion, a large problem is divided into smaller subproblems until a condition is reached at which the answer can be obtained directly.

Example from daily life: Imagine standing between two mirrors facing each other. You may see repeated reflections. Similarly, a recursive function repeatedly calls itself, but in a program, the calls must eventually stop.

Syntax of recursion in C

return_type function_name(parameters)
{
    if (base_condition)
    {
        return value;
    }
    else
    {
        return function_name(smaller_problem);
    }
}

A recursive function has two essential parts:

  1. Base case: The condition that stops further recursive calls.
  2. Recursive case: The part in which the function calls itself with a smaller or simpler problem.

Factorial of a number using recursion

The factorial of n is the product of all positive integers from 1 to n. By definition, 0! = 1.

C program

#include <stdio.h>

int factorial(int n)
{
    if (n == 0 || n == 1)
        return 1;

    return n * factorial(n - 1);
}

int main( )
{
    int n;

    printf("Enter a non-negative integer (0 to 20): ");
    scanf("%d", &n);

    if (n < 0 || n > 20)
    {
        printf("Invalid input\n");
        return 1;
    }

    printf("Factorial = %llu\n", factorial(n));

    return 0;
}

Output:

Enter a non-negative integer (0 to 20): 5
Factorial = 120

The program restricts input to 0 through 20 because the result must fit in unsigned long long on the C implementations targeted by this example.

Working of factorial(5)

5! = 5 * 4!
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
1! = 1

Therefore, 5! = 5 * 4 * 3 * 2 * 1 = 120.

The function calls move toward the base case, then the results are calculated as each call returns.

Sum of natural numbers using recursion

The sum of the first n natural numbers is:

S ( n ) = n + ( n − 1 ) + ( n − 2 ) + ⋯ + 1

We can define it recursively as:

S ( n ) = { 0 , n = 0 n + S ( n − 1 ) , n > 0

C program

#include <stdio.h>

int sum(int n)
{
    if (n == 0)
        return 0;

    return n + sum(n - 1);
}

int main( )
{
    int n = 5;

    printf("Sum = %d\n", sum(n));

    return 0;
}

Output:

Sum = 15

Explanation: S(5) = 5 + 4 + 3 + 2 + 1 + 0 = 15.

The base case is n == 0, and the recursive case is n + sum(n - 1).

Fibonacci series using recursion

The Fibonacci series is a sequence in which each term is the sum of the previous two terms.

The sequence begins:

0, 1, 1, 2, 3, 5, 8, 13, ...

Its recursive definition is:

F ( n ) = { 0 , n = 0 1 , n = 1 F ( n − 1 ) + F ( n − 2 ) , n ≥ 2

C program

#include <stdio.h>

int fibonacci(int n)
{
    if (n == 0)
        return 0;

    if (n == 1)
        return 1;

    return fibonacci(n - 1) + fibonacci(n - 2);
}

int main( )
{
    int i;

    printf("Fibonacci series: ");

    for (i = 0; i < 8; i++)
        printf("%d ", fibonacci(i));

    printf("\n");
    return 0;
}

Output:

Fibonacci series: 0 1 1 2 3 5 8 13

Important: This direct recursive approach is easy to understand, but it performs repeated calculations and becomes inefficient for large values of n. An iterative approach or memoization is generally preferable for larger sequences.

Reversing the digits of a number using recursion

A recursive function can process the last digit of a number and then continue with the remaining digits.

For example, reversing 1234 produces 4321.

C program

#include <stdio.h>

void reverseNumber(unsigned int n)
{
    printf("%u", n % 10);

    if (n >= 10)
        reverseNumber(n / 10);
}

int main( )
{
    unsigned int n = 1234;

    printf("Reversed number = ");
    reverseNumber(n);
    printf("\n");

    return 0;
}

Output:

Reversed number = 4321

Explanation:

  • n % 10 extracts the last digit.
  • n / 10 removes the last digit.
  • Recursion stops when the remaining number is less than 10.

For input 0, the program prints 0.

Greatest Common Divisor (GCD) using recursion

The greatest common divisor is the largest positive integer that divides two integers without a remainder.

Euclid's algorithm uses the relationship:

gcd(a, b) = gcd(b, a mod b)

The recursion stops when the second argument becomes zero.

C program

#include <stdio.h>

int gcd(int a, int b)
{
    if (b == 0)
        return a;

    return gcd(b, a % b);
}

int main( )
{
    printf("GCD = %d\n", gcd(48, 18));
    return 0;
}

Output:

GCD = 6

Working:

gcd(48, 18)
gcd(18, 12)
gcd(12, 6)
gcd(6, 0)

When b becomes zero, the function returns 6. This example uses positive integers.

Advantages of recursion

  1. Simplifies problem-solving: Some problems have natural recursive definitions.
  2. Improves readability: Recursive solutions can be shorter for problems such as tree traversal.
  3. Supports divide-and-conquer: Algorithms such as merge sort and quicksort use recursive problem decomposition.
  4. Useful for hierarchical structures: Recursion is suitable for traversing trees and similar structures.
  5. Matches mathematical definitions: Factorial, Fibonacci numbers, and GCD can be expressed recursively.

Disadvantages of recursion

  1. Memory overhead: Each active call requires storage for its execution context.
  2. Risk of stack exhaustion: Excessive recursive depth can exhaust available stack space.
  3. Function-call overhead: Repeated calls can be slower than an equivalent loop.
  4. Repeated calculations: Simple recursive Fibonacci calculation performs many duplicate computations.
  5. Difficult debugging: The order of calls and returns can be harder to trace.
  6. Incorrect base case: A missing or unreachable base case may lead to unbounded recursion.