Recursive Function
- Swastika Timilsina
Definition:
When a function calls itself directly or indirectly, it is called
recursive function.
The process of calling itself
is called recursion.
Properties of Recursive Function
• Anything that can be done with Iteration, can be done with
recursive and vice – versa.
• Recursion can sometimes give the most simple solution.
• Base Case is the condition which stops recursion.
• Iteration has infinite loop & Recursion has stack overflow.
Factorial:
#include<stdio.h> #include<stdio.h>
void pH(int count); int factorial(int n);
int main(){ int main(){
pH(5); printf("The factorial is
%d:",factorial(4));
return 0;
return 0; }
} int factorial(int n){
void pH(int count){ if(n==0||n==1){
if(count==0){ return 1;
return; }
} int factNm1=factorial(n-1);
printf("Hello world:\t"); int factN=factNm1*n;
pH(count-1); return factN;
} }
Why recursive function ? //combination
formula
#include<stdio.h> nr=(num-r);
void main(){ for(i=1;i<=nr;i++){
nrs=nrs*i;
int combination,num,r,i,n=1,nr,nrs=1,rfact=1;
}
printf("Enter the total number of terms:\n");
printf("Enter number of terms to be selected:\ for(i=1;i<=r;i++){
n"); rfact=rfact*i;
scanf("%d %d",&num,&r); }
for(i=1;i<=num;i++){
combination=n/(nrs*rfact);
n=n*i;
} printf("The combination
of %d and %d is
%d",num,r,combination);
}
#include <stdio.h>
int factorial(int n) {
int factorial(int n); if (n == 0 || n == 1)
int combination(int n, int r); return 1;
else
int main(){ return n * factorial(n - 1);
int x,r; }
int combination(int n, int r) {
printf("Enter the value of n:\n");
if (r == 0 || r == n)
scanf("%d",&x); return 1;
printf("Enter the value of r:\n"); else
scanf("%d",&r); return (factorial(n) / (factorial(r) *
factorial(n - r)));
printf("The combination of (%d,%d) is
}
%d",x,r,combination(x,r));
return 0;
}
Thank You!!!