× back Recursion Types of recursion Call Stack Iteration vs. recursion programs
Next Topic → ← Previous Topic

Recursion

Definition: Recursion is a programming technique where a function calls itself to solve a problem by breaking it down into smaller, similar subproblems. It involes solving a problem by reducing it to a smaller instance of the same problem.

Types of recursion

Direct Recursion:

  • In direct recursion, a function directly calls itself.
  • Example ↓
                    
#include <stdio.h>

void countdown(int n) {
    if (n == 0)
        return;
    printf("%d\n", n);
    countdown(n - 1);
}

int main() {
    countdown(5);
    return 0;
}
                    
                

Indirect recursion

  • In indirect recursion, a function calls another function(s) which eventually calls the original function.
  • Example ↓
                    
#include <stdio.h>

void function_B(int n);  // Forward declaration

void function_A(int n) {
    if (n == 0)
        return;
    printf("%d\n", n);
    function_B(n - 1);
}

void function_B(int n) {
    if (n == 0)
        return;
    printf("%d\n", n);
    function_A(n - 1);
}

int main() {
    function_A(5);
    return 0;
}
                    
                

Call Stack

Iteration vs. Recursion:

Programs

Sum of N

                       
#include <stdio.h>
int sum(int n)
{
    if (n == 0)
        return 0;
    return sum(n - 1) + n;
}
int main()
{
    int r;
    r = sum(5);
    printf("%d", r);
    return 0;
}
                       
                   

Factorial of N

                       
#include <stdio.h>
int fact(int n)
{
    if (n == 0)
        return 1;
    return fact(n - 1) * n;
}
int main()
{
    int r;
    r = fact(5);
    printf("%d", r);
    return 0;
}