In your code, print statement in reversePrint
should be like this,
System.out.println(numbers[numbers.length - 1] + ""); // for printing from left -> right
Recursion can be confusing to many of the people. Let me try my best to explain.
As you already may know, A Recursive programming contains basically a method which calls repeatedly itself until a certain condition is met. Note this point,
Until a certain condition is met
. This is very important in stopping the continuous execution of the method, which may lead to StackOverflow exception.
Okay coming to the point, in a recursive method, the first thing you need to do is to check if to continue execution or to return the control statement.
For simplicity, let us take only 10,20 as input for your example code.
- First, main method calls the recursive(
recursivePrint
) method for
printing the elements.
- Inside
reversePrint
method, as I said before, you are checking if to continue or to return the control by checking the number of elements in the array. This is because if there is no elements in array, then there is no point in continuing the program.
- Next, you are preparing the next set of array to pass to the
reversePrint
method by decrementing the array size(Current array size - 1). In 2nd point, you had 10,20 as two elements in array. Now, you are constructing new array with 10 as element(the idea here is to seperate individual elements from right to left, so that you can print it from right to left) as pass it to reversePrint
method. Thing to remember : Still some code is left behind to print the last element(which is 20
) which will be executed once this recursive method call is finished.
- Check if the array is empty, since we have 10 as the element, construct new array with of zero elements or empty array (
Current array size(which is ONE) - 1 = 0
) and call the recursivePrint method and pass this empty array. Thing to remember : Still some code is left behind to print the last element(which is 10
) which will be executed once this recursive method call is finished.
- Again, check if array is empty, since it is empty now, simply return to the control statement.
- Now the control goes back to execute the code which remained in previous step i.e
continuous to print the element
10
in 4th point.
- Since, the control statement reached the end of method, it goes back to print the element
20
as said in the 3rd Point.
- Again it reaches the end of method, and control statement returns back to the main method and prints empty string with no content.
Hope this helps you a little bit in understanding. All the best. Once you understand, it will be fun to work with it.