What is Recursion?

When a function calls itself then it is called Recursion. Recursion in c++ is a programming property and is implemented through function.

When a function calls itself it becomes a loop and hence it will never end. At the beginning of the function, there is a condition. which is called base condition. This condition if is true then the further calling of the function will be stopped.

In the above example, n==1 is the base condition and sum(n-1) is calling itself i.e recursion. So when sum function is called initially with an argument value of 5 i.e sum(5) then the recursive process will look like this:

Recursion in C++

The above function call is stored in the stack and traced back to complete the function operation. The Stack is maintained by Operating System, So there is no need to create and manage stack explicitly.

Types of Recursion

Recursion can be of two types:

  1. Head Recursion
  2. Tail Recursion

Head Recursion

In Head Recursion, the main body of the function comes after the recursive call statement i.e function calls itself at the beginning of the function.

In the above function, the function is calling itself before printing. Therefore if head(5) is called, the output will be:

Tail Recursion

In tail recursion, the function calls itself at the end of the function. Hence all main task of the function is done beforehand.

If the above function is called with value 5 i.e tail(5). Then the output will be:

All iteration can be converted into recursion. But Recursion is twice slower than iteration because it has to go down to all recursive call and again backtrack using the stack.

That’s all for the recursion in C++. If you have any doubt then comment below.

Leave a Reply

Close Menu