What is recursion and how to use recursion in programming. If you are new to programming, then recursion concept is tough to understand. In this post, i’ll explain the concept of recursion with example.
What is Recursion ?
In Recursion, function call itself repeatedly, until the base or terminating condition is not true. To understand this statement let’s take an example.
Suppose, we have to print a number between start to end range. Let’s print number between 1 to 10.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class Main { public static void main(String[] args) { //Called function to print 1 to 10 print(1, 10); } public static void print(int start, int end) { //Base condition if the value of start variable is greater than end then retun if(start > end) { return; } //print the value of start System.out.println(start); //call the method by incrementing the value of start print(start+1, end); } } |
It’s a much preferred way to write cleaner and shorter code for many complex problems.
Through recursion, you can reduce complex problem into smaller version.
Recursion Objective Questions for Practice.
Implement Binary Search Algorithm using Recursion.
Explanation of Recursion with Example
i) Factorial problem using recursion
1 2 3 4 5 6 7 8 9 10 11 12 13 |
int factorial(int number) { if(number <= 0) { return 1; } else { return number * factorial(number-1); } } |
Let’s say, you have passed 0 in factorial function in that case first condition is met and it returns 1.
Now let’s check how it work when 5 is enter .
1 2 3 4 5 |
return 5 * (factorial(4)); return 5 * (4 * factorial(3)); return 5 * (4 * (3 * factorial(2))); return 5 * (4 * (3 * (2 * factorial(1)))); return 5 * (4 * (3 * (2 * (1)))); |
Program to print Fibonacci series using recursion
Reverse a linked list using recursion
What happens if base condition is not defined in recursive programs.
In that case program will run until the system get out of memory.