bscodinglab

Recursion

Recursion is a programming technique where a function calls itself directly or indirectly to solve a problem. Recursion involves breaking down a problem into smaller sub-problems, solving each sub-problem separately, and combining the solutions to obtain the final solution.

The basic idea of recursion is to reduce the problem to a simpler version of itself, and keep reducing it until it becomes small enough to be solved directly, without recursion. Recursion can be implemented in many programming languages, including C, C++, Java, Python, and more.

Here is an example of a recursive function in C that calculates the factorial of a given number:-

#include <stdio.h>

int factorial(int n)

 {

    if (n == 0)

    {

        return 1;

    }

else {

        return n * factorial(n – 1);

        }

}

int main()

{

    int n = 5;

    int result = factorial(n);

    printf(“Factorial of %d is %d\n”, n, result);

    return 0;

}

  • In this example, the factorial() function takes an integer n as input and returns the factorial of n. The factorial of a number is defined as the product of all positive integers from 1 to that number. For example, the factorial of 5 is 5 x 4 x 3 x 2 x 1 = 120.
  • The factorial() function uses recursion to calculate the factorial of n. If n is equal to 0, the function returns 1, which is the base case of the recursion. Otherwise, the function calls itself with the argument n – 1 and multiplies the result by n. This recursive call continues until the base case is reached, at which point the recursion unwinds and the final result is returned.
  • Recursion is a powerful programming technique that can be used to solve a wide range of problems, including searching, sorting, tree traversal, and more. However, it can also be a source of errors and inefficiencies if used improperly, so it should be used with caution and care.