# How to write a recursive function c++

Then, move the biggest disk from start tower to final tower. The recursive code is usually smaller, more concise, more elegant, possibly even easier to understand, though that depends on ones thinking style. How will the monks solve this problem?

Another way to look at it is this, if we had a function to move the top three disks to the middle position, we could put the biggest disk in its place. If we do this the stack frame can be freed up. See advantages of tail recursion Head Recursion: A call is head-recursive when the first statement of the function is the recursive call.

A recursive function calls itself, the memory for a called function is allocated on top of memory allocated to calling function and different copy of local variables is created for each function call. Hint: Recursively find the factorial of the smaller numbers first, i.

What is the difference between direct and indirect recursion? It can be thought of like the Russian dolls that always have a smaller doll inside.

On the other hand, you might notice that the recursive versions use fewer or no local variables.

## Recursion in c++ geeksforgeeks

When any function is called from main , the memory is allocated to it on the stack. See advantages of tail recursion Head Recursion: A call is head-recursive when the first statement of the function is the recursive call. Basically, it is an if-statement that checks some variable for a condition such as a number being less than zero, or greater than some other number and if that condition is true, it will not allow the function to call itself again. So why use recursion? How a particular problem is solved using recursion? Now since we know that factorial of 2 works, factorial of 3 also works. The other main problem with recursion is that it can be slower to run than simple iteration. This is not the case with head recursion, or when the function calls itself recursively in different places like in the Towers of Hanoi solution. To move n disks or think of, say, 3 disks : Solve the problem for n - 1 disks i. Then again solve the problem for n - 1 disks but use the intermediate tower instead of the start tower i. This is not the case with my factorial solution above. How long will it take them?

The computer keeps function calls on a stack and once too many are called without ending, the program will crash. The idea is to represent a problem in terms of one or more smaller problems, and add one or more base conditions that stop the recursion.

Rated 10/10 based on 85 review