Question:
How to find the lowest and highest numbers in an array of ints?
Answer:
Use a for loop.
Code:
import java.util.*; public class LowestNumber { public static void main(String[] args) { int[] array = new int[15]; // populate array Random r = new Random(); for(int i=0;i<array.length;i++){ array[i]= r.nextInt(1000); } System.out.println("Contents: " + Arrays.toString(array)); // find smallest and largest numbers int small = array[0]; int large = array[0]; for(int i=0;i<array.length;i++){ if(array[i] <= small){ small = array[i]; } if(array[i] >= large){ large = array[i]; } } System.out.println("Smallest number: " + small); System.out.println("Largest number: " + large); } }
Output:
$ java LowestNumber Contents: [489, 283, 334, 331, 665, 643, 280, 100, 184, 642, 730, 560, 930, 517, 24] Smallest number: 24 Largest number: 930