Code Point Blog

Iam presenting here ,all type of knowledge if you want to interest knowing about any topic then click below thumbnail view button and knowing.

All Chapter Back to Home Page

recursion in C language

Recursion is a powerful and essential concept that allows a function to call itself directly or indirectly to solve a problem by breaking it down into smaller instances of the same problem.

A recursive function consists of two parts:

1.Base Case :A condition that specifies the simplest case where the function does not call itself again. It prevents the recursion from continuing indefinitely and provides a termination condition.

2.Recursive Case :The part of the function where it calls itself with a smaller instance of the problem. This allows the function to work on a smaller part of the problem until it reaches the base case.

Here's an example of a recursive function to calculate the factorial of a number:

    
     #include <stdio.h>
     int factorial(int n) { 
        if (n == 0 || n == 1) 
        return 1; 
        else 
        return n * factorial(n - 1); 
        } 

        int main() { 
        int num = 5; 
        printf("Factorial of %d is %d\n", num, factorial(num)); 
        return 0; 
        } 

        Output: 
        Factorial of 5 is 120 
                                    
    
    

In this example, the 'factorial' function is a recursive function that calculates the factorial of a given number `n`. It calls itself with a smaller value (`n - 1`) until it reaches the base case (`n == 0` or `n == 1`), where the recursion stops