Array: Find the largest element in an array

Q) Find the largest element in an array

Example:

Array: 33 93 29 40 36 81 46 14 60 24

Output:
Max Element= 93

public class ArrayMaxElement {
  
  public int maxElement (int [] sampleArray){
    int max= sampleArray[0]; //inititalize max to the first element of the array
    for (int i=0; i<sampleArray.length; i++){ //running a loop through the length of the array
      if (sampleArray[i]>max){ //compare each element to the max element
        max= sampleArray[i]; //if above condition if fulfilled replace max with sampleArray[i]
      }
    }
    return max; //return the largest element of the array
  }
}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close