RECURSION

Recursion: Recursion is a repetitive process in which a function calls itself.

–In recursion it calls itself directly or indirectly to solve a smaller version of its task until a final call is called which doesn’t require any other self call.

Source code:

#include <stdio.h>

int recursivefactorial(int n);

int main(){

    int n;

    printf(“\n enter the value to find the factorial”);

    scanf(“%d”,&n);

    int fact=recursivefactorial(n);

    if(fact!=0)

    printf(“\n the result is %d\n”,fact);

}

int recursivefactorial(int x){

  if(x==0 || x==1)

      return 1;

  else if(x<0){

        printf(“\n negative numbers not allowed”);

        return 0;

  }

  else

        return x*recursivefactorial(x-1);

}

Result:

Explanation: Initially 6 is passed to the function

Then it returns 6*recursivefactorial(5)

Then 5 is passed to the function

This returns 5*recursivefactorial(4)

Similarly this process continues till the value becomes 1

When 1 is passed to the function it returns 1 as mentioned in the function.So all the above recursive function calls are executed in the order of last in first out

This means the latest function call gets executed first.

Leave a Reply