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());
}
}
1ifarr != nulland otherwise0because of yourreturn minstatement in thewhileloop.nullnormally does not mean the same as an array of 0 elements. You are better off checking against null and throwing aNullPointerExceptionorIllegalArgumentExceptionif you encounter null for the array.