When reduced to a concise example, recursion can be quite a simple concept to grasp.
The below recursive function:
Takes a summand
float and a
index which defines the number of recursions. The function decreases this index with every recursion, and terminates the function with a "0" when the
value becomes 0.
Defining this function in code:
#include <bits/stdc++.h>
using namespace std;
double recurAdd(double x, int count)
{
if (count == 0){return 0;} // termination
return 10 + x + recurAdd(x, count - 1);
}
// Driver code
int main()
{
cout << recurAdd(0.5, 3);
return 0;
}
This small program will output 31.5 as a final value. We can represent the complete recursion in the following way:
Where the recursion can be broken down in the following way, from its first to last input iteration:
After the last input function has been terminated, the running of operations can be visualized to occur from the deepest to the outermost nest. I visualize this process with the following schematic:
Though not all recursion algorithms may follow this pattern, this visual has helped me simplify my understanding of recursion. I hope my visual helps you too.
-Andrew
Top comments (0)