It is a special case of calling a function when a function calls itself again and again.It forms a chaining f calling a function.
For example:-
void main(void)
{
cout<<"Hello Dear";
main( ); /* recursive call */
}
When executed, this program will display "Hello" on the screen indefinitely.
Another useful example of recursion is evaluation of factorial of a number. The factorial of number is expressed as a series of repetitive multiplications as,
For example:
factorial of 5 = factorial of 4 ⤫ 5
factorial of 4 = factorial of 3 ⤫ 4
factorial of 3 = factorial of 2 ⤫ 3
factorial of 2 = factorial of 1 ⤫ 2
factorial of 1 = 1
This statement will be transferred into recursive process in function as given below:
int factorial(int n)
{
int fact;
if(n==1)
return 1;
else
return(n*factorial(n-1));
}
Consider another example of finding value of Xy using recursion:
#include<iostream.h>
#include<conio.h>
int power(int x, int y)
{
if(y<1)
return(1);
else
return(x * power(x,--y));
}
void main( )
{
cout<<power(4,3);
getch( );
}
For example:-
void main(void)
{
cout<<"Hello Dear";
main( ); /* recursive call */
}
When executed, this program will display "Hello" on the screen indefinitely.
Another useful example of recursion is evaluation of factorial of a number. The factorial of number is expressed as a series of repetitive multiplications as,
For example:
factorial of 5 = factorial of 4 ⤫ 5
factorial of 4 = factorial of 3 ⤫ 4
factorial of 3 = factorial of 2 ⤫ 3
factorial of 2 = factorial of 1 ⤫ 2
factorial of 1 = 1
This statement will be transferred into recursive process in function as given below:
int factorial(int n)
{
int fact;
if(n==1)
return 1;
else
return(n*factorial(n-1));
}
Consider another example of finding value of Xy using recursion:
#include<iostream.h>
#include<conio.h>
int power(int x, int y)
{
if(y<1)
return(1);
else
return(x * power(x,--y));
}
void main( )
{
cout<<power(4,3);
getch( );
}
0 Comments:
Post a Comment