Recursion in Programming

What is Recursion?

Recursion is a most powerful technique in programming. In this technique, a function/method calls itself repeatedly until and unless the terminating condition is satisfied. It is widely used in many of the complex problems which include searching mechanisms, many discrete problems. Many algorithms also follow the concepts of recursion like Mathematical Induction, Euclid’s algorithm and more. In this tutorial, you will learn about recursion in programming.

Recursion to Infinity
Recursion to Infinity

Concept of Recursion

Recursion is a concept when you call a function in it. If you are a complete beginner, you might think that when a function keeps on calling itself will go to a never ending loop.  So you should place a condition in your recursive function, so when the condition is satisfied, the function stops calling itself.

Recursion is like a loop, so why should I use recursion instead of a loop?

There are problems which you can’t solve through loops and if you try to use loops rather than recursion you will not be able to get an optimized solution. For example, Fibonacci Series

0, 1, 1, 2, 3, 5, 8, 13, 21 . . .

Each number in Fibonacci Series is the sum of the previous two numbers. In case if you use loops, you will need nested loops, and your solution will be much more complex, but if you use recursion, you will just need to declare and initialize three variables to store the number of iterations on which condition should terminate the recursion and to save the previous two variables. The code for calculating the Fibonacci Series through recursion will be

Recursion in Java

Java also supports recursion. You can call a function within itself in Java. You can understand recursion in Java by a simple factorial example. If you are a complete beginner, and you don’t know about factorial, so the factorial of a number is the individual product of all the previous numbers. To understand factorial mathematically, you can take a number as the number and (n-1)*n.


Recursion in C#

Similar to Java recursion is also supported in C#, you can follow the same procedure as in Java for recursion. To understand the concept of recursion in C# I will repeat the same example of factorial in C#.


Hope that you like this tutorial. Stay tuned for more upcoming tutorials. Stay Blessed!