Java Program to find minimum element in an array

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


import java.util.Scanner;
public class ArrayMinimum {
    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 min = arr[0];
        int location = 1;
        for (i = 1; i < n; i++) {
            if (arr[i] < min) {
                min = arr[i];
                location = i;
        System.out.println("Minimum element of the array is:\t" + arr[location]);
        System.out.println("Location of minimum 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 minimum element and location in the array:

  1. The program initializes variables min to store the minimum element and location to store its index (location) within the array.
  2. It initializes min 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 minimum (min).
  4. If an element is less than the current minimum, it updates min to the new minimum and updates location to the index of this new minimum element.

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

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 min remains 7. 3 < 7, so min becomes 3 and location becomes 2. 9 > 3, so min remains 3. 4 > 3, so min remains 3. 6 > 3, so max remains 3.

Final Output: Minimum element of the array is: 3 Location of maximum element is: 2


Enter number of elements:
Enter 6 elements:
Minimum element of the array is:        7
Location of maximum element is:  2