java Q2. Write a method that returns the index of the smallest element in an arr
ID: 3760178 • Letter: J
Question
java
Q2. Write a method that returns the index of the smallest element in an array of doubles. If we have more than one equal smallest elements, return the smallest index. Use the following header: public static int indexofMin(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: Enter ten numbers: 3 5 2 7 4 11 5 2 2 3 17 The index of the min is 2 Q3. Modify the code developed in Q2 to include the following method: public static double getMin(double[] array) The getMin method returns the smallest element in an array of doubles. Use the indexOfMin method you developed in Q2 to implement getMin.Explanation / Answer
Q2.
import java.util.Scanner;
public class HelloWorld{
public static int indexOfMin(double[] array){
int i,ind=0;
double min=0;
for(i=0;i < array.length; ++i){
if (i==0){
min=array[i];
ind=i;
}
else if (array[i]<min) {
min=array[i];
ind=i;
}
}
return ind;
}
public static void main(String []args){
Scanner scnr = new Scanner(System.in);
double num = 0;
double [ ] myarray = new double [10];
int i,ind;
// Get user input
System.out.print("Please enter Ten numbers:");
i = 0;
do {
num = scnr.nextDouble();
myarray[i]=num;
i = i + 1;
} while (i <= 9);
ind=indexOfMin(myarray);
System.out.println("The index of the min is "+ind);
}
}
Q3.
import java.util.Scanner;
public class HelloWorld{
public static int indexOfMin(double[] array){
int i,ind=0;
double min=0;
for(i=0;i < array.length; ++i){
if (i==0){
min=array[i];
ind=i;
}
else if (array[i]<min) {
min=array[i];
ind=i;
}
}
return ind;
}
public static double getMin(double[] array){
return array[indexOfMin(array)];
}
public static void main(String []args){
Scanner scnr = new Scanner(System.in);
double num = 0;
double [ ] myarray = new double [10];
int i,ind;
// Get user input
System.out.print("Please enter Ten numbers:");
i = 0;
do {
num = scnr.nextDouble();
myarray[i]=num;
i = i + 1;
} while (i <= 9);
ind=indexOfMin(myarray);
System.out.println("The index of the min is "+ind);
System.out.println("The min value is "+getMin(myarray));
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.