- In C++ a function definition may contain a call to the function
being defined. In such cases the
function is said to be
**recursive**

Example

#include<iostream> |

Output

Calling print(3) |

- When a function is called, the computer plugs in the arguments for the parameters and begin to execute the code.
- If it should encounter a recursive call, it temporarily stops its computation because it must know the result of the recursive call before it can proceed.
- It saves all the information it needs to continue the computation later on, and proceeds to evaluate the recursive call.
- When the recursive call is completed, the computer returns to finish the outer computation.

- the function must be designed so that any call of the function must ultimately terminate with some piece of code that does not depend on recursion.
- The general outline of a successful recursive function definition
is
- One or more cases in which the function accomplishes its task by using one or more recursive calls to accomplish one or more smaller version of the task
- One or more cases in which the function accomplishes its task
without using any recursive calls.
These cases without any recursive calls are called
**base cases**or**stopping cases**.

- The most common way to ensure that a stopping case is eventually reached is to write the function so that some (positive) numeric quantity is decreased on each recursive call and to provide a stopping case for some "small" value.

What is the output of the following function

#include<iostream> |

Another example

#include<iostream> |

Output

2 |

- A recursive function can return a value of any type.

Example

#include<iostream> |

- Search if a key (a number) is in an array. If it is, find out the location.

Example

#include<iostream> |

Output

Enter a number to be located: 32 |

Output

Enter a number to be located: 31 |

- The above method is not very efficient. If you have 100 numbers in the array, it may take 100 comparisons to find the location of the key.
- A more efficient way is called
**binary search**

#include<iostream> |

- The array
`a[]`

must be in order. - The method is more efficient, it takes at most (log 2 of size) comparisons.