Implement a Java program that finds two neighbouring numbers in an array with th
ID: 3565813 • Letter: I
Question
Implement a Java program that finds two neighbouring numbers in an array with the smallest distance to each other. The function should return the index of the first number.
In the sequence 4 8 6 1 2 9 4 the minimum distance is 1 (between 1 and 2). The function should return the index of number 1 which is 3.
For each array element take user input to form the array.
Hint: Use Math.abs() to calculate the distance of two numbers. Math.abs() is used to give you the absolute value. For example the difference between 1 and 2 is 1-2 = -1. If you use Math.abs(1-2) it will give you 1 instead of -1.
Sample Run:
Enter the size of the array:
7
Please enter 7 positive integers:
4
8
6
1
2
9
4
The minimum difference is 1 and the numbers are 1 and 2. The index of 1 is 3.
Bye!!!
Explanation / Answer
import java.util.Scanner;
class calculateDistance
{
public static void main (String args[])
{
Scanner input = new Scanner(System.in);
int size;
int min;
int pos;
System.out.println("Enter the size of the array:");
size = input.nextInt();
int array[] = new int[size];
System.out.print("Please enter " + size + " positive integers:");
System.out.print(input.nextLine());
for (int i = 0; i < array.length; i++)
{
array[i] = Integer.parseInt(input.nextLine());
}
min = Math.abs(array[0] - array[1]);
pos = 0;
for (int i = 1; i < (array.length-1); i++)
{
if (Math.abs(array[i] - array[i+1]) < min)
{
min = Math.abs(array[i] - array[i+1]);
pos = i;
}
}
System.out.println("The minimum difference is "+ min + " and the numbers are " + array[pos] + " and " + array[pos+1] + ". The index of " + array[pos] + " is " + pos + ".");
System.out.println("Bye!!!");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.