Java Program to print the largest element in an array

In this program, the objective is to find the largest element present in the array and display it. This can be achieved by iterating through the array from the start to the end, comparing each element with a variable called max. Initially, we set max to the value of the first element in the array. During the loop, if any element is found to be greater than max, we update max with the value of that element. By the end of the loop, max will hold the largest element in the array.

In the given array, the initial value of the variable max is set to 25. During the iteration, each element of the array is compared with the current value of max. If an element is found to be greater than max, max is updated with the value of that element. Otherwise, the max remains unchanged. This process continues until all elements have been compared. By the end of the loop, max will store the largest element in the array.

Algorithm for a Java Program to print the largest element in an array

STEP 1: Start
STEP 2: Initialize the array arr[] with values {25, 11, 7, 75, 56}.
STEP 3: Set max = arr[0].
STEP 4: Repeat STEP 5 for each index i starting from 0, until i is less than the length of arr[].
STEP 5: If arr[i] is greater than max, update max with the value of arr[i].
STEP 6: Print “Largest element in a given array:”.
STEP 7: Print the value of max.
STEP 8: End.

Java Program to print the largest element in an array

public class LargestElement_array {  
    public static void main(String[] args) {  
  
        //Initialize array  
        int [] arr = new int [] {25, 11, 7, 75, 56};  
        //Initialize max with first element of array.  
        int max = arr[0];  
        //Loop through the array  
        for (int i = 0; i < arr.length; i++) {  
            //Compare elements of array with max  
           if(arr[i] > max)  
               max = arr[i];  
        }  
        System.out.println("Largest element present in given array: " + max);  
    }  
}

Output:

Largest element present in given array: 75

In conclusion, the provided Java program is designed to find and print the largest element in an array. It follows a step-by-step approach, initializing a variable called max with the value of the first element in the array. The program then iterates through the array, comparing each element with max. If an element is found to be greater than max, max is updated with the value of that element. Follow tutorials.freshersnow.com to learn more.