Suppose we have to print first 5 natural numbers (1,2,3,4,5),
but we can't just simply print those numbers one by one like the below code is doing neither we can have a function that will print an integer and just call it multiple times with different arguments
static void print(){
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);
}
Lets understand recursion...
Recursion simply means a
Function calling itself
The code below helps us realize the need of recursion.
The code uses number of methods to print the same output, it does only one function call with the starting first integer "1" later the print1 function prints "1" and then calls print2 method same for print3 and print4.The function body changes in print5 method it only print "5" and doesn't call any other function.
Its like all the functions are interlinked with each other.
Now how does recursion helps us.
Using recursion we can do the same task of printing first five positive integers with the help of only one function.
As we saw previously functions print1,print2,print3,print4 had the exact same function body, in the code below we are printing the same output but by using recursion.
public class NumbersExampleRecursion {
public static void main(String[] args) {
print(1);
}
static void print(int n){
if (n == 6){
return;
}
System.out.println(n);
print(n + 1);
}
}
Let's understand the code for better understanding
1.We have only one method called print() which is taking a integer as a parameter.
2.Now here's something new for us a if-condition.
let's find the answer to the question "Why we have a if-condition in the code?", "Why is it not returning anything?"
If-condition can also be called as a base condition, in recursion we always need a base condition and most of the time it is a if-condition.
return -> is just used as if the value of n becomes == 6 then it would just stop the code(calling of the function).
We need to write a base if-condition to make the recursive calling of the method stop.
No base condition means -> function calls will keep happening and the call stack will get filled after some calls, as it doesn't matter if we are calling different functions each time or same function every time like we are in the case of recursion, each function call takes a separate space in the call stack.
The if-condition in the code is stopping the function calling once the
n == 6 as till n == 6 it would have already printed the fifth integer "5".
After printing the integer we are basically incrementing the value of n.
Now the function will call itself with n+1 so as to get the desired output.
Why do we actually need recursion?
Ans: It helps us in solving bigger/complex problems in a simpler way by dividing that bigger problem into many smaller problems with minimum complexity.