logo of SA Coder
        Menu
sign in

      References



Recursion



Recursion is a powerful concept in programming that involves a function calling itself. In simple terms, recursion is a way of solving a problem by breaking it down into smaller subproblems, and then solving each subproblem using the same approach.



One classic example of recursion is calculating the factorial of a number. The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.



In programming, we can use recursion to implement the factorial calculation. Here is an example program in C language


copy

#include <stdio.h>

// this function returns n * (n-1)!
int factorial(int n)
{
    // base case: if n = 1, recursion is terminated
    if (n == 1)
    {
        return 1;
    }
    else
    {
        return n * factorial(n - 1); // recursive case: calling itself with n-1
    }
}

int main()
{
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);

    printf("%d! = %d\n", n, factorial(n)); // display factorial of n

    return 0;
}



Let's go through the code step by step. The factorial function takes an integer n as input and returns n * (n-1)!. This is the recursive case. The base case is when n is equal to 1, in which case the function returns 1. The base case is necessary to avoid infinite recursion and stack overflow errors.



In the `main` function, we first prompt the user to enter a number. Then we call the `factorial` function with the user input as the argument, and print out the result in the format `n! = result`.



When you run the program and input 5, you will get the output 5! = 120, which is the correct factorial of 5.



Recursion can be a very powerful and elegant way of solving problems in programming, but it can also be tricky to use correctly. One common mistake is not having a proper base case, which can lead to infinite recursion and stack overflow errors. Therefore, it is important to understand the concept and use it judiciously.



In conclusion, recursion is a fundamental concept in programming, and understanding how it works is essential for writing efficient and elegant code. The factorial calculation example presented here is just one of many possible applications of recursion. As you continue to explore programming, you will encounter many more examples of recursion and other powerful concepts that can help you solve complex problems.




Please login first to comment.