In this tutorial, we will write a java program to print the largest element present in an array. If you do not about the array and for loops working process then click the link below, as this program uses them.
The program below takes the number element and all the values of the elements from the user as input and finds the largest element among them in java.
Java Program to Find the Largest Element in an Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | //largest element in an array in java import java.util.Scanner; public class LargestElementsArray { public static void main(String[] args) { int num, largest; Scanner s = new Scanner(System.in); System.out.print("Enter the number of elements for an array:"); num = s.nextInt(); int a[] = new int[num]; System.out.println("Enter elements of array:"); for(int i = 0; i < num; i++) { a[i] = s.nextInt(); } largest = a[0]; for(int i = 0; i < num; i++) { if(largest < a[i]) { largest = a[i]; } } System.out.println("Largest elements in an array is:"+largest); } } |
Output:
Enter number of elements in the array:5
Enter elements of array:
4
67
89
32
4
Largest elements in an array is:89