Java Program to Find the Largest Element in the Array - The Coding Shala

Home >> Java Programs >> Find Largest Element in the Array

 In this post, we will learn how to Find the Largest Element in the given Array using Java.

Java Program to Find the Largest Element in the Array

In the given array, we need to print the maximum element of the array. The array can have negative and positive numbers.

Example 1:
Input: arr = {3, 5, 2, 5, -1, -33, 11}
Output: 11

Java Program: 

/**
 * https://www.thecodingshala.com/
 */


public class Main {

    public static void printLargest(int[] arr) {
        if (arr.length < 1) {
            System.out.println("Given array is empty");
        } else {
            int max = arr[0];
            for (int i=1; i<arr.length; i++) {
                if(arr[i] > max) {
                    max = arr[i];
                }
            }
            System.out.println("Largest element in the array is: " + max);
        }
    }

    public static void main(String[] args) {
        int[] arr = {3, 4, -6, 2, 7, -9, 11, -44, 22, 3, 6};
        printLargest(arr);
    }
}

Output: 

Largest element in the array is: 22


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala