Recursion in C++
A cyclic function call is called recusion. In simple when a function call itself again and again is called recursion. This call may be direct or indirect. So that there are two types of recursions.
Types of Recursion
-
Direct Recursion
-
Indirect Recursion
1. Direct Recursion
In this type of recursion function/method place a call to itself in its own body. This recursion involves only single function.
Example:
int printSeries ( int x ) {
cout<<x<<endl;
x--;
if(x == 1)
return 1;
else
return printSeries(x);
}
1. Indirect Recursion
Indirect recursion involves more than one function to produce a cyclic call. In this technique first calling function place a call to another function and subsequently first function is called from another function. Let suppose function calls in following way.
- Function A call function B
- Function B call function C
- Function C call function A
Example:
This example code will also generate the similar result as given in direct recursion.
int printSeries ( int x) {
cout<<x<<endl;
x = reduceNumber(x);
if(x == 1)
return 1;
else
return printSeries(x);
}
int reduceNumber( int w ) {
return --w;
}
Parts of Recursion
There are two parts of recursion.
- Base condition
- Recursive call
1. Base condition
This is the test condition which made recursive call false at some point. This base condition normally contain return statement.When this base condition become true the recursion ends.
Example:
Base condition for the given exapmle is as.
if(x == 1)
return 1;
2. Recursive Call
It is the satement which make a call to the function. it call to same function from its own body so that this is called recursive call.
Example:
From the above code example recursive call is as given.
return printSeries(x);
Difference between Recursion and Iteration:
Sr. | Recursion | Iteration |
1 | In recursion base condition is used for termination/completion of recursion. | Counter variable within condition is used for termination/completion of iteration. |
2 | Recursion use stack to complete the computations. | Iteration use only memory variables to complete computations. |
3. | Recursion implementation is complex. | Iterative solution of any problem is easy to implement. |
4. | Recursion required more memory. | Iteration require less meomry than recursion. |
5. | Recursion uses function.. | Iteration uses control strutures such as while loop, for loop or do while loop. |