C++ Recursion with example

The process in which a function calls itself is known as recursion and the corresponding function is called the recursive function. The popular example to understand the recursion is factorial function.

Base condition

In the above program, you can see that I have provided a base condition in the recursive function. The condition is:

if (n <= 1)
return 1;

The purpose of recursion is to divide the problem into smaller problems till the base condition is reached. For example in the above factorial program I am solving the factorial function f(n) by calling a smaller factorial function f(n-1), this happens repeatedly until the n value reaches base condition(f(1)=1). If you do not define the base condition in the recursive function then you will get stack overflow error.

Direct recursion vs indirect recursion

Direct recursion: When function calls itself, it is called direct recursion, the example we have seen above is a direct recursion example.

Indirect recursion: When function calls another function and that function calls the calling function, then this is called indirect recursion. For example: function A calls function B and Function B calls function A.

No, because it queues up the multiplier from the first function call of the n*f(n-1). So when n is finally <= 1 it returns it to the function call before. So instead of n* f(n-1), it would be n * 1. From here it would have all the previous values of n stored and solve the equation.