Introduction

In our programming life there are situations where we have to write code to perform some repetitive tasks and in those situations recursion can become our best friend, but the problem with recursion is that it is sometimes complicated to understand.

Recursion is one of the topics that we all are taught in our student life but at that time we do not give much attention to this guy, and when we start our life as a programmer this same guy comes again in our life to irritate us and laugh at us.

So this is my little effort to introduce you to recursion so that you can use it in your code without any doubt and hesitation.

Though many of the problems can be easily solved using iteration and loops, there are some problems like graphs and tree where recursion can come in handy.

In this article I’ll be focusing more on algorithms rather than on programming language -- you can choose programming language of you own choice. For demonstration purposes I’ll be using JavaScript & C# because most of the programmers are familiar with the same.

Recursion

Wikipedia says “Recursion is a method where the solution to a problem depends on solution to smaller instances of the same problem.” What I understood is that we need to break the big problem into similar smaller pieces in order to tackle the complete problem. Divide and Rule.

Recursion

Recursion calls itself to solve other pieces of problem until all pieces gets solved. There are two main components of a recursion method:

Let’s understand what is happening in the flow chart. In every recursive method there is a base case which terminates the function if condition is satisfied else the method calls itself to return the value or it may call itself successively and the chain continues unless one of the called method meets the required condition to terminate the chain.

We will understand the above points when we will solve some real problems.

Recursive problems

Conclusion

We leveraged the power of recursion in various situations. All we need to solve any problem with the help of recursion is to find the base case and the reduction step for given problem. Proper algorithm needs to be created before writing any code. I hope the above examples are interesting and easy enough to help you understand the basics of recursion.