Recursion is a process in which a defined function calls itself as long as the condition is correct, such functions are called recursive.
For e.g :
1 |
factorial(n)= n*factorial(n-1) |
You can see factorial of n calls itself again with different input.so it is recursive.
Syntax
1 2 3 4 5 6 7 8 9 |
returnType function_name(dataType input) { if(condition) { /*Function will call itself as long as condition true*/ output=function_name(input); } return output; } |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include<stdio.h> long double factorial(long int num_copy); /*function prototype declaration*/ int main() { unsigned long int num; long double factorial_result; printf("\nEnter Num :"); scanf("%ld",&num); factorial_result=factorial(num); //function Calling printf("factorial(%ld)=%Lf\n",num,factorial_result); return 0; } long double factorial(long int num_copy) /*function definition */ { long double fact=1; if((num_copy==1)||(num_copy==0)) { return 1; } else if(num_copy<0) { printf("factorial(%ld)=Not defined ,please input Positive values",num_copy); } else { fact=fact*num_copy*factorial(num_copy-1); } return fact; } |
You can see in above example, let’s take a number 5
factorial_result=factorial(5); //function Calling
factorial(5) jumps into its definition first time from its main with input 5.
factorial(5-1) calls its definition first time from its own definition with input 4.
fact=1 x 5 x factorial(5-1);
factorial(4-1) calls its definition second time from its own definition with input 3.
fact=1 x 5 x 4 x factorial(4-1);
factorial(3-1) calls its definition third time from its own definition with input 2.
fact=1 x 5 x 4 x 3 x factorial(3-1);
factorial(2-1) calls its definition second time from its own definition with input 1.
fact=1 x 5 x 4 x 3 x 2 x factorial(2-1);
factorial(1)satisfy the first condition (input==1) so its return 1 to calling function i.e factorial(1).
fact=1 x 5 x 4 x 3 x 2 x 1;
output (value stored in fact) returns from factorial function and save into facorial_result.
facorial_result=120;
So you can see that from step2 to step 5 everytime factorial(input) function calls itself from its definition.So factorial() function is recursive.