(Find the index of the smallest element) Write a method that returns the index o
ID: 3811104 • Letter: #
Question
(Find the index of the smallest element) Write a method that returns the index of the smallest element in an array of integers. If the smallest number of such elemnets is greater than 1, return the smallest index. Use the following header:
public static int indexOfSmallestElement(double[] array)
Write a test program that prompts the user to enter ten numbers, invokes this method to return the index of the smallest element, and displays the index.
Sample Run for Exercise07 10 Enter input data for the program. Sample data provided below. You may modify it.) 1.9 2.5 3.7 2 1 6 3 4 5 2.5 Show the Sample Output Using the Preceeding Input command java Exercisee7 1 Enter ten numbers 1.9 2.5 3.7 2 1.5 6 3 4 5 2.5 The index of the minimal value i 4 commandExplanation / Answer
HI, Please find my implementation.
Please let me know in case of any issue.
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
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.