Find Largest Element of an Array in Java


Write a Java Program to find largest element of an array.

Click Here to View the Solution!
public class LargestNumber {
   public static void main(String[] args) {
   double[] numArray = { 65.9,-24.9,90.0,78.15,19.5,54.0,3.2,-96.1 };
   double largest = numArray[0];
         for (double num: numArray) {
             if(largest < num)
                 largest = num;
System.out.format("Largest element of the given array = %.2f", largest);
Click Here to View the Output!
Largest element of the given array = 90.00
Click Here to View the Explanation!
  • This program deals with detecting the largest number in an array of elements.
  • Here is an array of up to 8 floating point numbers, stored in numArray.
  • Initially the first element at 0th index is being considered to be the largest element so as to be compared with the rest of the numbers that exist in the array. Therefore, it is stored in largest variable.
  • The for-each loop checks for each element in the array if it is greater than the current value of largest variable.
  • If so is the case, then that number is swapped with the existing value of largest variable and the loop runs again.
  • The loop continues until it compares all the values with the value stored in the largest variable.
  • When the loop terminates, the value held in largest is displayed after being rounded up to 2 decimal places i.e. 90.00 in this case.

%d bloggers like this: