Java How To - Largest Element in an Array
Find the Largest Element in an Array
Scan the array and keep track of the biggest value found so far:
Example
int[] nums = {12, 7, 25, 3, 18};
int largest = nums[0];
for (int n : nums) {
if (n > largest) {
largest = n;
}
}
System.out.println("Largest element: " + largest);
Explanation: We start by assuming the first element is the largest. Then we loop through the array and update the variable whenever we find a bigger value.