fb popup

/* remove if it's exist in your template */

Recursion

Recursion means calling the function by itself.

 Ex:-
#include<stdio.h>
int factorial(int);
void main()
{
int value;
printf("Enter a value to obtain it's factorial:");
scanf("%d",&value);
int result=factorial(value);
printf("factorial of %d is %d",value,result);
}

int factorial(int f)
{
if(f!=0)
return(f*factorial(f-1));
else
return 1;

}
Output:-  

Recursion output


Explanation:- value in "value " is sent to 'f' The main logic that is going on :-
If the user input is 4

1.)factorial(4)
2.)4*factorial(3)

3.)As factorial (3)=>3*factorial(1)
4.)substitute 3 in 2

5.)4*3*factorial(2)

6.)now factorial(2)==>2*factorial(1)
7.)substitute 6 in 5

8.)4*3*2*factorial(1)

9.)factorial(1)==>1*factorial(0);
10.)substitute 9 in 8

4*3*2*1*factorial(0)
factorial(0)==>1;
Therefore,4*3*2*1*1===>24

No comments:

Post a Comment