Write a Java program to find the position (index) of the largest element in an array.
Java Fundamentals: Building Strong Foundations (Article) (Program)
10
Given Input:
int[] arr = {45, 12, 89, 34, 67};
Expected Output:
Largest element: 89
Position (index): 2
Program:
class LargestElementPosition {
public static void main(String[] args) {
int[] arr = {45, 12, 89, 34, 67};
int max = arr[0];
int position = 0;
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
position = i;
}
}
System.out.println("Largest element: " + max);
System.out.println("Position (index): " + position);
}
}
Output:
Explanation:
The program compares all elements and keeps track of the largest value and its index.
Largest element: 89 Position (index): 2
Program:
class LargestElementPosition { public static void main(String[] args) { int[] arr = {45, 12, 89, 34, 67}; int max = arr[0]; int position = 0; for (int i = 1; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; position = i; } } System.out.println("Largest element: " + max); System.out.println("Position (index): " + position); } }
Output:
Explanation:
The program compares all elements and keeps track of the largest value and its index.