Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why println is being executed in this recursive piece of code?

In this code arrLength starts with four and then keeps being decremented until it reaches zero.
At the moment it reaches zero it should not execute what is inside the if block anymore.
But what is happening is that when it reaches zero it still executes the println line.
Not understanding how that println line is being executed since that line is inside the if block and nothing inside the if block should execute when arrLength gets to zero.
At the end it prints 5, 6, 2, 1 while in my understanding it should print nothing never executing the println line.

class ArrayElements{
 
    public void printElements(int arr[], int arrLength){
        if(arrLength != 0){
            arrLength--;
            printElements(arr, arrLength);
            System.out.println(arr[arrLength]);
        }
    }
}
public class Main {
 
    public static void main(String[] args) {
        int arr[] = {5,6,2,1};
        int arrLength = arr.length;
 
        ArrayElements mv = new ArrayElements();
        mv.printElements(arr, arrLength );
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

An easy way to understand what is happening is to modify your printElements method like this:

public void printElements(int arr[], int arrLength){
    System.out.println("arrLength value is " + arrLength);
    if(arrLength != 0){
        arrLength--;
        printElements(arr, arrLength);
        System.out.println(arr[arrLength]);
    }
}

The output will be:

arrLength value is 4
arrLength value is 3
arrLength value is 2
arrLength value is 1
arrLength value is 0
5
6
2
1

As you can see you made 5 recursives calls but only print 4 values. The reason been the second println is not executed when arrLength is equal to 0.

This means that when arrLength is 0 you do not enter the if condition.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading