Lesson 16: Recursion
Recursion is defined as a function calling itself. It is in some ways similar to a loop because it repeats the same code, but it requires passing in the looping variable and being more careful. Many programming languages allow it because it can simplify some tasks, an it is often more elegant than a loop.
A simple example of recursion would be:
void recurse()
{
recurse(); //Function calls itself
}
int main()
{
recurse(); //Sets off the recursion
return 0; //Rather pitiful, it will never be reached
}
This program will not continue forever, however. The computer keeps function calls on a stack and once too many are called without ending, the program will terminate. Why not write a program to see how many times the function is called before the program terminates?
#include
void recurse(int count) //The count variable is initalized by each function call
{
cout<