Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Q2. Write a method that returns the index of the smallest element in an array of

ID: 3760374 • Letter: Q

Question

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: 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));
}
}