Arrays
Java Program to Find Largest Element of an Array
A Java program to find the largest element in an array.
Problem Description
Write a Java program to find the largest element in an array.
Code
public class LargestElement {
public static void main(String[] args) {
double[] numArray = { 23.4, -34.5, 50.0, 33.5, 55.5, 43.7, 5.7, -66.5 };
double largest = numArray[0];
for (double num : numArray) {
if (largest < num)
largest = num;
}
System.out.format("Largest element = %.2f", largest);
}
}Output
Largest element = 55.50Explanation
- Initialize: Assume the first element is the largest.
- Compare: Iterate through the array and compare each element with the current largest.
- Update: If an element is larger, update the
largestvariable.
