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. →