Question:
How do you find the lowest and highest numbers in a 2D array?
Answer:
You can use a nested for loop.
Code:
import java.util.*; public class LowestNumber { public static void main(String[] args) { int[][] array = new int[5][2]; // populate array Random r = new Random(); for(int i=0;i<array.length;i++){ for(int j=0;j<array[i].length;j++){ array[i][j] = r.nextInt(1000); } } System.out.println("Contents: " + Arrays.deepToString(array)); // find smallest and largest numbers int small = array[0][0]; int large = 0; for(int i=0;i<array.length;i++){ for(int j=0;j<array[i].length;j++){ if(array[i][j] <= small) small = array[i][j]; if(array[i][j] >= large) large = array[i][j]; } } System.out.println("Smallest number: " + small); System.out.println("Largest number: " + large); } }
Output:
$ java LowestNumber Contents: [[658, 462], [594, 729], [412, 18], [575, 66], [224, 666]] Smallest number: 18 Largest number: 729