Recursion
Recursion is derived from the word recur which means repetition
There are two basic requirement for recursion:
i) The function must call itself again and again
ii) The function must have an exit condition.
When to use recursion:
Recursion can be used for any function involving loop i.e, all loops can be converted into recursion
void recurse ()
{
recurse (); //Function call itself
}
int main ()
{
recurse (); // set off recursion
return();
}
Example of Recursion
/* Sum of N nos. through recursion */
# include <iostream.h>
int add (int x);
main()
{
int n;
cout<<"Enter any positive no. \n";
cin>>n;
cout<<"The sum of first"<<n<<"integer="<<add(n)<<endl;
return 0;
}
int add (int n)
{
if (n==0)
return 0;
else return[n+add(n-1)]
}
There are two basic requirement for recursion:
i) The function must call itself again and again
ii) The function must have an exit condition.
When to use recursion:
Recursion can be used for any function involving loop i.e, all loops can be converted into recursion
- A recursion procedure or function is one that repeats itself through calls made on it.
- Repeat calls are terminated as soon as certain condition is satisfied.
- Every recursive function must contain a way to get out of the recursive process
- Recursive process is complex and involved
- Recursive function may be defined as a repeated iteration , which calls itself until a certain condition is met.
void recurse ()
{
recurse (); //Function call itself
}
int main ()
{
recurse (); // set off recursion
return();
}
Example of Recursion
/* Sum of N nos. through recursion */
# include <iostream.h>
int add (int x);
main()
{
int n;
cout<<"Enter any positive no. \n";
cin>>n;
cout<<"The sum of first"<<n<<"integer="<<add(n)<<endl;
return 0;
}
int add (int n)
{
if (n==0)
return 0;
else return[n+add(n-1)]
}
No comments