Recursion in C Programming

Recursion is a programming technique where a function calls itself in order to solve a problem. It's a powerful concept that allows solving complex problems by breaking them down into simpler, similar subproblems.
A recursive procedure has the following two properties:

  • There must be a specific criterion called the base case for which the procedure does not call itself.
  • Each time it calls itself (directly or indirectly), it must be getting closer to reaching the base case.

For example, consider the process of counting down before launching a rocket. Imagine a function called launchCountdown(seconds) that decrements the seconds until the rocket takes off. This function could invoke itself using launchCountdown(seconds - 1) until it reaches the base case of seconds equaling 0. Then, it halts the recursion and simply returns, indicating the rocket is set to launch. With each recursive call, the countdown approaches the base case of seconds being 0.

Example
main()
{
    printf("Small Code");
    main();
}

In the example,main funnction is a recursion function but in this example their is no controlling point by which we could controlled the recursion function.
So,a function to be complete c recursion function,their should be these to things.

  • A function should be recursion.
  • Their should be a controlling point.

Types of recursion

On the basis of calling
  • Tail Recursion
  • Non-Tail Recursion

Tail Recursion

Tail recursion function is one where every recursion all is a last thing done by the function before returning and thus produces a function value tail recursion a pattern are used that compile is a pattern of used that can be compile or interprate avoiding the efficiency.

Example
#include<stdio.h>
int factorial(int n) {
    return factorial1(n, 1);
}
int factorial1(int n, int A) {
    if (n == 1)
        return A;
    else
        return factorial1(n - 1, n * A);
}
int main() {
    int x, fact;
    printf("Enter the number=");
    scanf("%d", &x);
    fact = factorial(x);
    printf("%d", fact);
}

Non-Tail Recursion

Non-tail recursion refers to a type of recursion where there are additional operations after the recursive call in a function. In non-tail recursion, the result of the recursive call must be further processed before it can be returned.

#include<stdio.h>
int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1; // Base case
    } else {
        // Recursive call
        return n * factorial(n - 1);
    }
}
int main() {
    int result = factorial(5);
    printf("Factorial of 5 is: %d\n", result); // Factorial of 5 is: 120
}