Largest element in an Array with examples

In this tutorial we will learn How to Find Largest Element in an Array with some examples. The largest element is the element which is greater than all the other elements inside the array.

Largest Element in An Array
FlutterTPoint

Explanation:
1. Create a method which takes an array.
2. Declare a int variable and assign the first value of the array.
3. Iterate the loop and assign the value to that variable if the array’s element value is grater that it.

Code to Find the Largest Element in an Array

Java


public class Test {

    static void largestElementInArray(int arr[]){
        int largest = arr[0];
        for(int i = 0; i<arr.length; i++){
            if(largest < arr[i]){
                largest = arr[i];
            }
        }

        System.out.print("largest element = " + largest);
    }

    public static void main(String[] args) {
        int arr2[] = { 1, 200, 3, 4, 5, 6 };
        largestElementInArray(arr2);

    }
}

We will get the following answer.

Answer : largest element = 200

JavaScript


function largestElement(arr){
    var largest = arr[0];
    for(let i = 0; i<arr.length; i++){
        if(largest < arr[i]){
            largest = arr[i];
        }
    }

   console.log("largest element = " + largest);
}

var numbers = [1, 13, 45, 122, 45, 23]
largestElement(numbers)

Answer : largest element = 200

Time complexity: O(N), for both the above functions.
Space: O(1)

Do you know How To Remove Duplicates from an Array?

Thank you for reaching out this tutorial. You can comment in the comments section below for any doubt or query. You can learn more about this topic from here.

Thank You FlutterTPoint
Thank You FlutterTPoint

Don’t miss new tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment

Scroll to Top