Recursive functions are functions that calls itself. This calling maybe direct or indirect. This process is called recursion. Using recursion we can solve certain problems very easily. The problems we have done using recursion are:
- Sum of n natural numbers
- Finding the nth element in Fibonacci series.
- Factorial of a number.
SUM OF n NATURAL NUMBERS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
int sumn(int n) | |
{ | |
if(n == 0) | |
{ | |
return 0; | |
} | |
else if(n == 1) | |
{ | |
return 1; | |
} | |
else | |
{ | |
return n + sumn(n-1); | |
} | |
} | |
int main() | |
{ | |
int n,ans; | |
printf("Enter the nth value: "); | |
scanf("%d",&n); | |
ans = sumn(n); | |
printf("The sum of first %d natural numbers is %d",n,ans); | |
getch(); | |
return(0); | |
} |
FINDING THE nTH ELEMENT IN THE FIBONACCI SERIES
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
int fibo(int n) | |
{ | |
if(n == 0) | |
{ | |
return 0; | |
} | |
else if(n == 1) | |
{ | |
return 0; | |
} | |
else if(n == 2) | |
{ | |
return 1; | |
} | |
else if(n == 3) | |
{ | |
return 1; | |
} | |
else | |
{ | |
return fibo(n-1) + fibo(n-2); | |
} | |
} | |
int main() | |
{ | |
int n,ans; | |
printf("Enter the value of n: "); | |
scanf("%d",&n); | |
ans = fibo(n); | |
printf("The %d th element in the fibonacci series is %d",n,ans); | |
getch(); | |
return(0); | |
} |
FACTORIAL OF A NUMBER
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
int facto(int n) | |
{ | |
if(n == 0) | |
{ | |
return 1; | |
} | |
else if(n == 1) | |
{ | |
return 1; | |
} | |
else | |
{ | |
return n * facto(n-1); | |
} | |
} | |
int main() | |
{ | |
int n,ans; | |
printf("Enter the number to find factorial: "); | |
scanf("%d",&n); | |
ans = facto(n); | |
printf("%d ! = %d",n,ans); | |
getch(); | |
return(0); | |
} |
Comments
Post a Comment