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?

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




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(

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

System.out.println("Number with higher value is "+

Apr 3, 2014