Forum : Need Help in comparing adjacent elements in an array
Brief description  about Online courses   join in Online courses
View Priyanka  Taware 's Profile

Need Help in comparing adjacent elements in an array

Hi Sir,
I am doing assignment to compare adjacent elements in an array. Output should print higher element, between 2 elements compared.

I am trying to do this in if loop, which compares ar[i] with ar[i 1], and so on, to print higher of 2 numbers. This gives output as 5 higher numbers.

Can you please explain what is correct way to do this program?


Program:
package Operators;

public class CompareArray {

public static void main(String[] args) {

int expArray[]= {10,60,20,50,80,40,90,70,30,100};

System.out.println("Comparing Elements in an Array");
System.out.println("===================================");
for (int i=0;i<expArray.length;i ){

if(expArray[i 1]>expArray[i]){
int val=expArray[i 1];
System.out.println("Number with higher value is:" val);

}

}

}

}
Output:
Comparing Elements in an Array
===================================
Number with higher value is:60
Number with higher value is:50
Number with higher value is:80
Number with higher value is:90
Number with higher value is:100
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Operators.CompareArray.main(CompareArray.java:13)

Asked by Priyanka Taware | Apr 1, 2014 |  Reply now
Replies (1)
View java teacher 's Profile
You can try this logic mentioned below

for(i=0;i<9;i++)
{
System.out.println("Number with higher value is "+
(a[i]>a[i+1]?a[i]:a[i+1]));
}

Apr 3, 2014