In: Computer Science
Using Java Write a method that returns the index of the smallest 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 indexOfSmallestElement (double[] array)
import java.util.Scanner;
public class SmallestElement {
public static int indexOfSmallestElement(double[] array){
int smallest_index = 0;
for(int i=1; i<array.length; i++)
if(array[smallest_index] > array[i])
smallest_index = i;
return smallest_index;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter 10 numbers: ");
double arr[] = new double[10];
for(int i=0; i<10; i++)
arr[i] = sc.nextDouble();
System.out.println("Smallest element is at index: "+indexOfSmallestElement(arr));
}
}
/*
Sample run:
Enter 10 numbers:
1.9 2.5 3.7 2 1.5 6 3 4 5 2.5
Smallest element is at index: 4
*/