Given an array length 1 or more of ints, return the difference between the largest and smallest values in the array. Note: the built-in Math.min(v1, v2) and Math.max(v1, v2) methods return the smaller or larger of two values.
or
public class bigDiff { public static void main(String[] args) {
int[] nums ={2, 10, 7, 2}; //min and max value of array int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE;
// for each loop
for (int minInt: nums) { if(minInt<min){ min=minInt; } }System.out.println(min); // max value of array for (int maxInt: nums) { if(maxInt>max){ max=maxInt; } }System.out.println(max); System.out.println(max-min); } }
or
public static void main(String[] args) { int[] nums ={10, 3, 5, 6}; int min = nums[0]; int max = nums[0]; for (int i = 0 ; i < nums.length-1; i++) { min = Math.min(nums[i],min); max = Math.max(nums[i],max); } System.out.println(max-min); }
Komentarze
Prześlij komentarz