Recursion

In C programming language recursion is the process of repeating items itself. In the recursion program the solution to the base case is provided and the solution of the big problem is exposed in terms of small problem. We using recursion programmers need to be careful to define exit condition from the function otherwise it will go into a infinite loop.

Why we Learn C Programming?

  • Recursion is more useful for the tasks but they cannot be applied to all the problems and they can be defined in terms of similar sub tasks.
  • Mainly recursion are applying for sorting, searching and the traversal problems.
  • In C language recursion involves several numbers of recursive calls.

let’s see the example of recursion in C language

Calculate the factorial number

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

Output

Enter the number5

factorial=120

Example sum of natural numbers using recursion

#include <stdio.h>
int sum(int n);

int main() {
    int number, result;

    printf("Enter a positive integer: ");
    scanf("%d", &number);

    result = sum(number);

    printf("sum = %d", result);
    return 0;
}

int sum(int n) {
    if (n != 0)
       
        return n + sum(n-1); 
    else
        return n;
}

Output

Enter a positive integer:3
sum = 6

Submit your review
1
2
3
4
5
Submit
     
Cancel

Create your own review

The Technical Funda
Average rating:  
 0 reviews