-moz-user-select:none; -webkit-user-select:none; -khtml-user-select:none; -ms-user-select:none; user-select:none;

Tuesday 9 June 2015

Recursion in C++

Hello and Asalam o Alikum. Many students are confused with the concept of recursion in C++.So,today I will try to discuss all the basics of recursion in C++.

Recursion

A recursive function is a function that calls itself,either directly or indirectly(through another function).A recursive function is called to solve a problem. If the function is called with a base case, then function simply returns a result. If a function is called with a more complex problem, it typically divides the problem into two conceptual pieces,a piece that the function knows how to do and the piece that the function doen not know.

To make recursion feasible, the latter piece must resemble the original problem, but be a slighty smaller version. This new problem looks like the original problem, so the function launches a fresh copy of itself to work on the smaller problem. This is referred to as recursive call and is also called the recursive step.

The basic idea behind solving problems via recursion is to break the instance of the problem into smaller and smaller pieces until the pieces are so small they can be solved trivially. 

General example

For example, we can define the operation "find your way home" as:
  1. If you are at home, stop moving.
  2. Take one step toward home.
  3. "find your way home".
Here the solution to finding your way home is two steps (three steps). First, we don't go home if we are already home. Secondly, we do a very simple action that makes our situation simpler to solve. Finally, we redo the entire algorithm.(reference of general example has been taken from reference)

No comments:

Post a Comment