In: Computer Science
Write a Java method that returns the index of the largest element in an array of integers. If the number of such elements is greater than 1, return the smallest index. Use the following header: public static int indexOfLargestElement(double[] array) Write a test program that prompts the user to enter ten numbers, invokes this method to return the index of the largest element, and displays the index.
The required JAVA program is given below,
import java.util.Arrays;
import java.util.Scanner;
class Ideone {
// Finding the index of largest element
public static int indexOfLargestElement(double[]
array){
double maxValue = array[0];
int maxIndex = 0;
// finding maximum value
for (int i = 0; i < array.length; i++) {
if (maxValue
< array[i]) {
maxValue = array[i];
}
}
// finding first index of max
value
for (int i = 0; i <
array.length; i++) {
if (maxValue ==
array[i]) {
maxIndex=i;
}
}
return maxIndex;
}
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
// input length of array , it can
be hardcoded as 10
System.out.println("Enter the length of the input
array:");
int length = s.nextInt();
double [] array = new double[length];
// entering the elements
System.out.println("Enter the elements:");
for(int i=0; i<length; i++ ) {
array[i] = s.nextDouble();
}
// printing output
System.out.println("Index of
largest element is :");
System.out.println(indexOfLargestElement(array));
}
}
SCREENSHOT