Ths is a question from a past paper. I have been asked to create a static method arrayMin to find the smallest value in the array arr.
I have to use a while loop and on each iteration, the variable min will return the smallest number from the first i elements.
Is there a way to do this without calling another method/for loop and strictly using the while loop, as the question is only worth 4%(including writing loop invariants and javadoc). Not sure if I am overcomplicating the problem.
public class Revision {
public static int arr[] = new int[] { 5, 8, 4, 3, 6, 2 };
public static int min = 1;
public static int arrayMin() {
int i = 0;
if (arr == null) {
return 0;
} else {
while (i < arr.length) {
// some function/method call to find smallest number of arr[i]
i++;
return min;
}
}
return min;
}
public static void main(String[] args) {
System.out.println(arrayMin());
}
}
A couple of things:
arrayMinmethod;minshould be a localarrayMinvariable, not static;minshould be initialized toInteger.MAX_VALUE. If you initialize it with1, and2happens to be the min value of the array, you’ll never return it;return min, the method ends. There’s probably some confusion over the the variable min will return the smallest number from the first i elements phrase. It probably means that in each iteration, the variableminwill have (not return) the smallest number from the firstielements.Here’s a refactor: