Recursion is the technique of making a method call itself. To be achieved you need to have test statement to check for condition to stop recursion else it will continue infinite until your program crash 🙂
Example program of recursion. First check for the condition to stop recursion. In this case if the number is less or equal to zero. Every call of the recursion method will add the number and call itself with n-1 number.
Lets call method with 5. Then we will observe this steps:
- recursionMethod will call itself every time with parameter – 1 from the previous call. In total it will call itself 6 times until parameter reach zero
- Recursion bottom will be printed. This mean that recursion will stop and the first return number will be zero
- every time sum from the previous call of the method will be added to the current parameter of the method. This will be done 5 times
- In the end we get the final result which is equal to 0 + 1 + 2 + 3 + 4 + 5 = 15.
As a second parameter is added empty string with two spaces ” ” for every call of the recursion. Then this spaces are added to the print statements to visually show how the recursion looks like.
public class MainClassVisualRecursion { public static void main(String[] args) { // Here we will calculate 0 + 1 + 2 + 3 + 4 + 5 = 15 int result = recursionMethod(5, ""); System.out.println("Final answer: " + result); } public static int recursionMethod(int number, String space) { System.out.println(space + "recursionMethod called. Parameter number is: " + number); // Recursion need to make check to stop // check if number negative or zero // if yes stop recursion if(number <= 0) { System.out.println(space + "Here is the bottom of the recursion"); return number; } // Recursion need to call itself recursively else { int sumFromPreviousRecursion = recursionMethod(number - 1, space + " "); int sum = number + sumFromPreviousRecursion; String data = space + "previous recursion sum: %d, current parameter : %d, current sum: %d"; System.out.printf(data, sumFromPreviousRecursion, number, sum); System.out.println(); return sum; } } }
Output:
recursionMethod called. Parameter number is: 5
recursionMethod called. Parameter number is: 4
recursionMethod called. Parameter number is: 3
recursionMethod called. Parameter number is: 2
recursionMethod called. Parameter number is: 1
recursionMethod called. Parameter number is: 0
Here is the bottom of the recursion
previous recursion sum: 0, current parameter : 1, current sum: 1
previous recursion sum: 1, current parameter : 2, current sum: 3
previous recursion sum: 3, current parameter : 3, current sum: 6
previous recursion sum: 6, current parameter : 4, current sum: 10
previous recursion sum: 10, current parameter : 5, current sum: 15
Final answer: 15