Java Program to find maximum element in an array

Java program finds the maximum element in an array entered by the user and also prints its location within the array.


import java.util.Scanner;
public class ArrayMaximum {
    public static void main(String[] args) {
        int n, i;
        Scanner sc = new Scanner(;
        int[] arr = new int[10];
        System.out.println("Enter number of elements:");
        n = sc.nextInt();
        System.out.println("Enter " + n + " elements:");
        for (i = 0; i < n; i++)
            arr[i] = sc.nextInt();
        int max = arr[0];
        int location = 1;
        for (i = 1; i < n; i++) {
            if (arr[i] > max) {
                max = arr[i];
                location = i;
        System.out.println("Maximum element of the array is:\t" + arr[location]);
        System.out.println("Location of maximum element is:\t " + (location + 1));

The program initializes integer variables n and i. n is used to store the number of elements in the array, and i is used as a loop counter. An integer type array arr of size 10 is created to store the elements.

The user is prompted to Enter numbe of elments using System.out.println("Enter number of elements:"); and the user input is read using Scanner object using Scanner sc = new Scanner(; and inputted value is stored in n variable. Then again user is prompted to enter each element.

The main logic to find maximum element and location in the array:

  1. The program initializes variables max to store the maximum element and location to store its index (location) within the array.
  2. It initializes max with the first element of the array (arr[0]) and location with 1 (index starts from 1).
  3. A loop iterates over the array starting from index 1 (i = 1) and compares each element with the current maximum (max).
  4. If an element is greater than the current maximum, it updates max to the new maximum and updates location to the index of this new maximum element.

After finding the maximum element and its location, the program prints them to the user console.

Consider an example to illustrate step by step process of finding maximum number:

Let's say the user enters the number of elements as 5 and the elements of the array are: 7, 3, 9, 4, 6. 7 > 7, so max remains 7. 3 < 7, so max remains 7. 9 > 7, so max becomes 9 and location becomes 3. 4 < 9, so max remains 9. 6 < 9, so max remains 9.

Final Output: Maximum element of the array is: 9 Location of maximum element is: 3


Enter number of elements:
Enter 6 elements:
Maximum element of the array is:        87
Location of maximum element is:  2