Recursion is a powerful tool for writing algorithms supported in some programming languages like C, C++. Recursion is a process in which a function calls itself and it is applicable to problems where something can be defined in terms of itself. Recursion technique is used to solve simple to highly challenging problems. Let’s walk through some simple examples to understand the concept of recursion and how it is implemented in C++ language. Same fundamentals are applicable for any other language which supports recursion.

Role of System Stack in Recursive Algorithms
Whenever, a function f1( ) makes a call to another function f2( ), information about the current state of f1( ) is stored in the system stack so that when control returns from f2( ), we can resume operations in f1( ). Same concept is applicable to recursive algorithms. When a function func( ) makes a call to itself, the information about the current call instance is saved in system stack and it is popped out when the function execution is over
( boundary condition is met ). Consider the following program :

Can you predict the output of this program ?
We are calling the function with n = 5. So, the first cout statement is executed which prints 5 and then there is a recursive call to the function with n = 4. Thus, the state of the current call is stored in the system stack i.e the value of n and the address of the next statement after the function call ( in this case, 2nd cout statement ). This continues till n becomes 0 i.e boundary condition is met. At this point of time, we have printed 5 4 3 2 1. Now, it’s time to pop out the contents of system stack in last-in-first-out ( LIFO ) order. Last instance stored in the stack was n = 1 and the address of 2nd cout statement. So, the 2nd cout statement is executed and 1 is printed. When next instance is popped out, 2 is printed. This continues till all the function call instances are popped out.
Final output of the above program is : 5 4 3 2 1 1 2 3 4 5
The usage of system stack is the most basic funda of recursion.

Tower of Hanoi ProblemTower of Hanoi is a mathematical puzzle. It consists of three PEGS ( Source, Destination and Auxiliary ). Source peg consists of disks of different sizes such that they form a conical shape. The objective is to move all the disks from source to destination peg using an auxiliary peg with the following constraints :1 ) Only one disk can be moved at a time.2 ) We can never place a larger disk on top of a smaller disk.
Following figure illustrates the problem statement :

Suppose, we are given n disks on the source peg. We need to display all the moves which are required to move the disks from source peg to destination peg. Let’s formulate a recursive solution :1 ) Move top n – 1 disks from source peg to auxiliary peg2 ) Move the only disk present in source peg to destination peg3 ) Move the n – 1 disks from auxiliary peg to destination peg
Following program illustrates the recursive solution :