What is recursion in C language - What is recursion in C language with example - recursion kya hai - recursion ka use kya hai

What is recursion in C language with example?


Recursion in C language is a programming technique where a function calls itself to solve a problem. Instead of using iteration (loops), a recursive function breaks down a complex problem into smaller, more manageable sub-problems and solves each sub-problem by calling itself. Recursion is based on the concept of a base case, which serves as the termination condition to stop the recursive calls.
 
To illustrate recursion in C, let's look at an example of calculating the factorial of a positive integer using a recursive function:

#include <stdio.h>
// Recursive function to calculate the factorial of a positive integer
unsigned long long factorial(int n) {
    // Base case: If n is 0 or 1, the factorial is 1
    if (n == 0 || n == 1) {
        return 1;
    } else {
        // Recursive call to the factorial function
        return n * factorial(n - 1);
    }
}
 
int main() {
    int num;
     printf("Enter a positive integer: ");
    scanf("%d", &num);
     if (num < 0) {
        printf("Factorial is not defined for negative numbers.\n");
    } else {
        unsigned long long result = factorial(num);
        printf("Factorial of %d is %llu\n", num, result);
    }
     return 0;
}

In this example, the factorial function calculates the factorial of a positive integer n. The base case is when n is 0 or 1, in which case the function returns 1, as the factorial of 0 and 1 is defined as 1. For any other positive integer n, the function makes a recursive call to itself with the argument n - 1 and multiplies the result by n. This continues until the base case is reached, and the function starts unwinding the recursive calls, returning the final factorial value.
 
For example, if you input 5, the program will output:

Factorial of 5 is 120

Recursion is a powerful concept, but it should be used judiciously, as excessive recursion can lead to stack overflow and decreased performance. It is essential to have a proper base case and ensure that the recursion terminates after a finite number of steps.

Comments