Recursion
Recursion is an interesting and sometimes
useful programming technique whereby you call the function that you’re in.
Of course, if this is all you do, you’ll keep calling the function
you’re in until you run out of memory, so there must be some way to
“bottom out” the recursive call. In the following example, this
“bottoming out” is accomplished by simply saying that the recursion
will go only until the cat exceeds
‘Z’:[31]
//: C03:CatsInHats.cpp
// Simple demonstration of recursion
#include <iostream>
using namespace std;
void removeHat(char cat) {
for(char c = 'A'; c < cat; c++)
cout << " ";
if(cat <= 'Z') {
cout << "cat " << cat << endl;
removeHat(cat + 1); // Recursive call
} else
cout << "VOOM!!!" << endl;
}
int main() {
removeHat('A');
} ///:~
In removeHat( ), you can see
that as long as cat is less than ‘Z’,
removeHat( ) will be called from within
removeHat( ), thus effecting the recursion. Each time
removeHat( ) is called, its argument is one greater than the current
cat so the argument keeps increasing.
Recursion is often used when evaluating
some sort of arbitrarily complex problem, since you aren’t restricted to a
particular “size” for the solution – the function can just
keep recursing until it’s reached the end of the problem.