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

Time:05-07

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 );
    }
}

CodePudding user response:

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.

  • Related