To find the biggest element, keep a variable for the largest seen so far. Start it at the first element (arr[0]), then compare each remaining element and update when you find something bigger. Starting at arr[0] (not 0) keeps it correct even for all-negative arrays.
arr[0]
int[] nums = {3, 7, 2, 9, 4}; int max = nums[0]; for (int i = 1; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; } } System.out.println(max); // 9
The loop starts at index 1 because max already holds element 0.
max
▶ Try it: run this to find the largest value. Change the numbers and re-run.
To find the maximum, what should max start at?
What is the maximum of {3, 7, 2, 9, 4}?
{3, 7, 2, 9, 4}
Inside the loop, when do you update max?
Type the maximum this prints:
int[] a = {5, 2, 8, 1}; int max = a[0]; for (int i = 1; i < a.length; i++) { if (a[i] > max) { max = a[i]; } } System.out.println(max);
True or false?