Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function.
void recursion()
{
recursion(); /* function calls itself */
}
void main()
{
recursion();
}
|
The C programming language supports recursion, i.e., a function to call itself. But while using recursion, programmers need to be careful to define an exit condition from the function,
Otherwise it will go into an infinite loop
//Fibonacci series using function with return value
#include<stdio.h>
#include<conio.h>
int fibo(int n);
void main()
{
int n, i;
printf("\n Enter how many no of terms you want of Fibonacci series : ");
scanf("%d", &n);
printf("\nFibonacci Series of %d terms is as follows: \n",n);
for(i=1;i<=n;i++)
{
printf("%5d", fibo(i));
}
getch();
}
int fibo(int n)
{
int r;
if(( n == 1) || ( n == 0))
return 0;
else if(n == 2)
return 1;
else
return (fibo(n-1) + fibo(n-2));
}
|
//Write a program to find out factorial of a number using recursion funciton
#include<stdio.h>
#include<conio.h>
int fact(int n);
void main()
{
int n,f1;
printf("\nENTER N:");
scanf("%d",&n);
f1 = fact(n);
printf("\nN = %d",n);
printf("\nFact = %d",f1);
getch();
}
int fact(int n)
{
int f;
if(n==1)
return 1;
else
f=n*fact(n-1);
return f;
}
|
0 comments:
Post a Comment