How to compare two consective numbers of an array in java

Viewed 31

I am trying to compare two consecutive numbers of an array and print the largest one in every iteration. I have written below code but its giving unexpected responses. Can somebody please check and help me understand the mistake.

PS: I just started learning java.

public class Test {
    
    public static void main(String [] args){

       int[] list = {6,0,4,2,9};
       int current;
        for(int j=0; j<list.length-1; j++){
            if(list[j]>list[j+1]){
                current = j;
            }else{
                current = j+1;
            }
        System.out.print(current + " ");
        }
    }
}

Expected response: 6 4 4 9
Actual response: 0 2 2 4 
1 Answers

Ok so your code is just returning j which here is used as the number in youy for loop.

In your if you're using j as an index to get the value in list matching that index; but in the rest of your for loop you're setting current to the value of j and not the value of list at the index j.

What you'll want to print is the value of list[j] and not j.

In fact, if you look closely [0 2 2 4] are the indexes of [6 4 4 9]

Related