Java program to find the largest element in array
Given an array of numbers, write a java program to find the largest element in the given array.
Example:
int[] a = {1, 5, 3, 9, 2, 8, 2}
Largest Element: 9
Java 代码
public class LargestElementInArray {
public static void findLargestElement(int[] a) {
if (a == null || a.length == 0) {
return;
}
int largest_element = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] > largest_element) {
largest_element = a[i];
}
}
System.out.println("Largest element in array: " + largest_element);
}
public static void main(String[] args) {
int[] a = {1, 5, 3, 9, 2, 8, 2};
findLargestElement(a);
}
}