Write a Java program that asks the user to enter an array of integers in the main method. The program should prompt the user for the number of elements in the array and then the elements of the array. The program should then call a method named minGap that accepts the array entered by the user as a parameter and returns the minimum 'gap' between adjacent values in the array. The main method should then print the value returned by the method. The gap

Respuesta :

Answer:

In Java:

import java.util.*;

class Main {  

public static void minGap(int intArray[], int arrlength) {  

 if(arrlength <2){return;}

 int minm = Math.abs(intArray[1] - intArray[0]);  

 for (int i = 2; i < arrlength; i++)  

  minm = Math.min(minm, Math.abs(intArray[i] - intArray[i - 1]));  

 System.out.print("Minimum Gap = " + minm);  

}  

public static void main(String arg[]) {  

 Scanner input = new Scanner(System.in);

 int arrlength;

 System.out.print("Array Length: ");

 arrlength = input.nextInt();

 int[] intArray = new int[arrlength];

 for(int i = 0;i<arrlength;i++){

     intArray[i] = input.nextInt();

 }

 minGap(intArray, arrlength);  

} }

Explanation:

The minGap method begins here

public static void minGap(int intArray[], int arrlength) {

This checks if array length is 1 or 0. If yes, the program returns nothing

 if(arrlength <2){return;}

If otherwise, this initializes the minimum gap to the difference between the 0 and 1 indexed array elements

 int minm = Math.abs(intArray[1] - intArray[0]);  

This iterates through the array elements

 for (int i = 2; i < arrlength; i++)  

This checks for the minimum gap

  minm = Math.min(minm, Math.abs(intArray[i] - intArray[i - 1]));  

At the end of the iteration, the minimum gap is printed

 System.out.print("Minimum Gap = " + minm);  

}  

The main method begins here

public static void main(String arg[]) {  

 Scanner input = new Scanner(System.in);

This declares the length of the array

 int arrlength;

This prompts the user for array length

 System.out.print("Array Length: ");

This gets the user input

 arrlength = input.nextInt();

This declares the array

 int[] intArray = new int[arrlength];

The following iteration gets input for the array

 for(int i = 0;i<arrlength;i++){

     intArray[i] = input.nextInt();

 }

This calls the minGap method  

minGap(intArray, arrlength);  

}