# Alternate Numbers Difference Program in java

## Question:

Write a java program to read an array of integer elements. The program should find the difference between the alternate numbers in the array and find the index position of the smallest element with largest difference. If more than one pair has the same largest difference consider the first occurrence.

Note : When taking the difference take the absolute value i.e. neglecting the sign. Example : If it is 3-10=-7, consider it as 7.

If the array size is less than 3,Display “Invalid array size”.

Sample Input1:

6

4

3

2

10

8

6

Sample Output1:

1

Explanation :

Here alternate number difference means

4-2, 3-10, 2-8, 10-6
Neglect the sign So diff is 2,7,6,4
Largest diff is 7 —–> 3-10, here the smallest number is 3 and its index is 1. Hence the output is 1.

Sample Input2:

7

7

6

2

2

3

1

8

Sample Output2:

2

Sample Input3:

-1

Sample Output3:Invalid array size

### CODE:–

```import java.util.Scanner;
public class Main
{
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of an array:");
int n=sc.nextInt();
if(n>0)
{

int arr[]=new int[n];
System.out.println("Enter the array elements:");
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
}

String output="";

for(int j=0;j<n;j++)
{
if(arr[j]>=0&&arr[j]<10)
{
if(arr[j]%2!=0)
{
output=output.concat(String.valueOf(arr[j]));
}
}
}
if(output.equals(""))

else
System.out.println(output);
}

else
{
System.out.println("Invalid array size");
}
}
}```

Next:
Scroll to Top