Recursion function in C language
Recursion
A function is said to be recursive if it can be defined in the terms of itself. Recursion is a programming technique that allows the programmer to express operation in terms of themselves. In C, this take the form of a function that call itself.
Syntax:
void recursion() {
recursion();
}
Program: write a program to find out the factorial of a number using Recursion function.
Code:
int factorial(int x)
{
if(x==1)
return 1;
else
return x*factorial(x-1);
}
void main ()
{
int n,f;
printf("Enter the no ");
scanf("%d",&n);
f=factorial(n);
printf("\nfactorial of %d is =%d",n,f);
}
Output:
Enter the no 6
factorial of 6 is =720
--------------------------------
Program: Write a program to find out the Fibonacci series using Recursion function.
code:
#include<stdio.h>
int Fibonacci(int n)
{
if ( n == 0 || n==1 )
return n;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}
void main()
{
int n, i = 0,c;
printf("Enter the number of seriese:");
scanf("%d",&n);
printf("Fibonacci series is \n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
}
Output:
Enter the number of seriese:12
Fibonacci series is
0
1
1
2
3
5
8
13
21
34
55
89
--------------------------------
Program: Write a program to find sum of first n natural numbers using recursion.
code-
#include<stdio.h>
int sum(int n){
if(n==0)
return n;
else
return n+sum(n-1);
}
int main(){
int num, add;
printf("Enter a positive number: ");
scanf("%d",&num);
add=sum(num);
printf("Sum=%d",add);
}
Output:
Enter a positive number: 15
Sum=120
--------------------------------
Advantages of Recursion
Recursion can be used to replace complex nesting code by dividing the problem into same problem into same problem of its sub-type.
Disadvantages of Recursion
It is difficult to think the logic of a recursive function. it is also difficult to debug the code containing recursion.
Comments
Post a Comment