Lesson 37 of 60 – Recursion in C
62%

Recursion in C

Recursion is a programming technique in which a function calls itself to solve a problem. A recursive function normally contains two important parts: a base case and a recursive case.

Note: The base case stops recursion. Without a proper base case, a recursive function may continue calling itself until the program runs out of available stack space.

1. What is Recursion?

Recursion occurs when a function calls itself directly or indirectly.

void show()
{
    show();
}

Here, the function show() calls itself. This is a simple example of recursion, but it has no stopping condition.

2. Recursive Function

A function that calls itself is called a recursive function.

void count(int number)
{
    if (number == 0)
    {
        return;
    }

    printf("%d\n", number);

    count(number - 1);
}

The function continues by calling itself with a smaller value.

3. Base Case

The base case is the condition that stops the recursive calls.

void count(int number)
{
    if (number == 0)
    {
        return;
    }

    printf("%d\n", number);

    count(number - 1);
}

Here, number == 0 is the base case.

4. Recursive Case

The recursive case is the part of the function that calls the same function again.

void count(int number)
{
    if (number == 0)
    {
        return;
    }

    printf("%d\n", number);

    count(number - 1);
}

The statement count(number - 1) is the recursive case.

5. Simple Recursion Example

#include <stdio.h>

void countDown(int number)
{
    if (number == 0)
    {
        return;
    }

    printf("%d\n", number);

    countDown(number - 1);
}

int main()
{
    countDown(5);

    return 0;
}

Output:

5
4
3
2
1

6. How Recursion Works

Suppose we call countDown(3).

countDown(3)
    ↓
countDown(2)
    ↓
countDown(1)
    ↓
countDown(0)
    ↓
return

When the base case is reached, the recursive calls stop.

7. Recursion and the Call Stack

Each function call creates a new stack frame. Recursive calls continue creating stack frames until the base case is reached.

count(3)
count(2)
count(1)
count(0)

After reaching the base case, the calls return in reverse order.

8. Recursive Factorial

Factorial is one of the most common examples of recursion.

int factorial(int number)
{
    if (number == 0)
    {
        return 1;
    }

    return number * factorial(number - 1);
}

For example:

5! = 5 × 4 × 3 × 2 × 1 = 120

9. Factorial Program

#include <stdio.h>

int factorial(int number)
{
    if (number == 0)
    {
        return 1;
    }

    return number * factorial(number - 1);
}

int main()
{
    printf("Factorial = %d", factorial(5));

    return 0;
}

Output:

Factorial = 120

10. Factorial Execution

For factorial(4), the recursive calls can be viewed as:

factorial(4)
4 × factorial(3)
4 × 3 × factorial(2)
4 × 3 × 2 × factorial(1)
4 × 3 × 2 × 1 × factorial(0)
4 × 3 × 2 × 1 × 1
24

The final result is 24.

11. Recursive Sum of Numbers

int sum(int number)
{
    if (number == 0)
    {
        return 0;
    }

    return number + sum(number - 1);
}

Calling sum(5) calculates:

5 + 4 + 3 + 2 + 1 = 15

12. Recursive Sum Program

#include <stdio.h>

int sum(int number)
{
    if (number == 0)
    {
        return 0;
    }

    return number + sum(number - 1);
}

int main()
{
    int result = sum(5);

    printf("Sum = %d", result);

    return 0;
}

Output:

Sum = 15

13. Recursive Countdown

void countdown(int number)
{
    if (number <= 0)
    {
        return;
    }

    printf("%d\n", number);

    countdown(number - 1);
}

The function prints a number and then calls itself with a smaller value.

14. Recursive Counting from 1 to N

void countUp(int number)
{
    if (number == 0)
    {
        return;
    }

    countUp(number - 1);

    printf("%d\n", number);
}

Here the recursive call occurs before the printf(), so the numbers are printed in increasing order.

15. Recursion for Fibonacci Numbers

The Fibonacci sequence is another common example of recursion.

int fibonacci(int number)
{
    if (number <= 1)
    {
        return number;
    }

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

This implementation directly follows the recursive definition of the Fibonacci sequence.

16. Fibonacci Program

#include <stdio.h>

int fibonacci(int number)
{
    if (number <= 1)
    {
        return number;
    }

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

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

    return 0;
}

Output:

0 1 1 2 3 5 8 13

17. Recursive Power Function

int power(int base, int exponent)
{
    if (exponent == 0)
    {
        return 1;
    }

    return base * power(base, exponent - 1);
}

For example, power(2, 4) calculates 2 × 2 × 2 × 2, giving 16.

18. Recursive GCD Function

The greatest common divisor can be calculated recursively using the Euclidean algorithm.

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

    return gcd(b, a % b);
}

The recursion stops when the second value becomes zero.

19. Recursive GCD 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", gcd(48, 18));

    return 0;
}

Output:

GCD = 6

20. Recursive String Length

A string length can also be calculated recursively using a pointer.

int length(char str[])
{
    if (str[0] == '\0')
    {
        return 0;
    }

    return 1 + length(str + 1);
}

The function moves through the string one character at a time until it reaches the null character.

21. Recursive Reverse Printing

Recursion can be used to process a string and print its characters in reverse order.

void reversePrint(char str[])
{
    if (str[0] == '\0')
    {
        return;
    }

    reversePrint(str + 1);

    printf("%c", str[0]);
}

The recursive call occurs before printing, so characters are printed while the calls return.

22. Recursion with an Array

int arraySum(int numbers[], int size)
{
    if (size == 0)
    {
        return 0;
    }

    return numbers[size - 1]
         + arraySum(numbers, size - 1);
}

The function processes one array element during each recursive call.

23. Recursive Array Sum Program

#include <stdio.h>

int arraySum(int numbers[], int size)
{
    if (size == 0)
    {
        return 0;
    }

    return numbers[size - 1]
         + arraySum(numbers, size - 1);
}

int main()
{
    int numbers[] = {10, 20, 30, 40};

    printf("Sum = %d",
           arraySum(numbers, 4));

    return 0;
}

Output:

Sum = 100

24. Direct and Indirect Recursion

There are two common forms of recursive calls.

  • Direct recursion: A function calls itself directly.
  • Indirect recursion: One function calls another function, which eventually calls the first function.
void A()
{
    B();
}

void B()
{
    A();
}

This example shows the basic structure of indirect recursion. A suitable stopping condition is required.

25. Recursion vs Loop

Many recursive problems can also be solved using loops.

Using a loop:

int factorial(int number)
{
    int result = 1;

    for (int i = 1; i <= number; i++)
    {
        result *= i;
    }

    return result;
}

A recursive solution may be more natural for problems that are defined in terms of smaller versions of the same problem.

26. Stack Overflow in Recursion

Every recursive call uses stack space. If recursion continues too deeply, the program can run out of stack space.

void test()
{
    test();
}

This function has no base case, so it keeps calling itself. Recursive functions should have a reachable stopping condition.

27. Common Recursion Mistakes

  • Forgetting the base case.
  • Using a base case that can never be reached.
  • Not moving the input toward the base case.
  • Using recursion unnecessarily for a simple problem.
  • Creating very deep recursion and exhausting stack space.
  • Returning the wrong result from a recursive call.
int count(int number)
{
    if (number == 0)
    {
        return 0;
    }

    return 1 + count(number - 1);
}

Always check how each recursive call moves toward the stopping condition.

28. Complete Recursive Factorial Program

#include <stdio.h>

int factorial(int number)
{
    if (number <= 1)
    {
        return 1;
    }

    return number * factorial(number - 1);
}

int main()
{
    int number;

    printf("Enter a number: ");
    scanf("%d", &number);

    if (number < 0)
    {
        printf("Factorial is not defined for negative numbers.");
    }
    else
    {
        printf("Factorial = %d",
               factorial(number));
    }

    return 0;
}

29. When Should You Use Recursion?

Recursion can be useful when a problem naturally consists of smaller versions of the same problem.

  • Factorial calculations
  • Fibonacci calculations
  • Tree-like structures
  • Divide-and-conquer algorithms
  • Recursive searching and processing
  • Problems that can be divided into smaller similar problems

For simple repeated calculations, a loop may often be easier to understand and more memory-efficient.

30. Practice Programs on Recursion

Practice the following programs:

  1. Print numbers from N to 1 using recursion.
  2. Print numbers from 1 to N using recursion.
  3. Calculate factorial using recursion.
  4. Calculate the sum of numbers from 1 to N.
  5. Calculate the power of a number recursively.
  6. Generate Fibonacci numbers using recursion.
  7. Find the GCD of two numbers recursively.
  8. Find the sum of array elements recursively.
  9. Find the length of a string recursively.
  10. Print a string in reverse using recursion.

For every recursive program, identify the base case and the recursive case before writing the code.

📌 Key Points

  • Recursion occurs when a function calls itself.
  • A recursive function should have a base case.
  • The base case stops further recursive calls.
  • The recursive case performs another call to the same function.
  • Each recursive call uses stack space.
  • Factorial is a common example of recursion.
  • Fibonacci numbers can be calculated recursively.
  • Recursion can be used with arrays and strings.
  • Indirect recursion occurs when functions call each other recursively.
  • Deep or uncontrolled recursion can cause stack overflow.

🧠 Quick Quiz

Question: What is the condition that stops a recursive function from making further recursive calls called?