Write a program to read an integer array and find the index of larger number

Write a program to read an integer array and find the index of larger number of the two adjacent numbers with largest difference. Print the index.

Input and Output Format:

Input consists of n+1 integers, where n corresponds the size of the array followed by n integers.

Output consists of an Integer (index).

Refer sample output for formatting specifications.

Sample Input :

6

4

8

6

1

9

4

Sample Output :

4

[In the sequence 4 8 6 1 9 4 the maximum distance is 8 (between 1 and 9). The function should return the index of the greatest of two. In this case it is 9 (which is at index 4). output = 4.]

package com.demo;
 
import java.util.Scanner;
 
public class Main
{
 
public static void main(String[] args)
{
int a[]=new int[20];
int max=checkDifference(a);
System.out.println(max);
}
 
private static int checkDifference(int[] a)
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
for(int i=0;i<n;i++)
{
a[i]=s.nextInt();
}
int max=0,index=0;
for(int i=0;i<n;i++)
{
int d=Math.abs(a[i]-a[i+1]);
if(d>max)
{
max=d;
if(a[i]>a[i+1])
{
index=i;
}
else
{
index=i+1;
}
}
}
return index;
}}

 

Add a Comment

Your email address will not be published. Required fields are marked *

5 − four =