Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement a Java program that finds two neighbouring numbers in an array with th

ID: 3565817 • 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

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 3 (of number 1).

class LangFund3{
    static void smallestDistance(int [] array){
    
        int smallest = Math.abs(array[0]-array[1]);
        int index = 0;
        for(int i=1; i<array.length-1; i++){
            int value = Math.abs(array[i]-array[i+1]);
            if(value< smallest){
            smallest= value;
            index = i;
            }
                
        }
        System.out.println(smallest);
        System.out.println(index);    
            
    }
    public static void main(String [] args){
        int []arr= new int[]{4,8,6,1,2,9,4};
        smallestDistance(arr);
    }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote