Write a program to find the maximum and minimum element in an array


This Java program takes user input for the size of an array, then prompts the user to enter the elements of the array. It then finds and prints the maximum and minimum elements of the array. Here is how the program works:

  • First, it imports the Scanner class from the java.util package to allow user input.
  • It declares a class called Array_Max_Min.
  • It declares a main method that takes no arguments and has a return type of void.
  • Within the main method, it creates a new Scanner object called input to take user input.
  • It prompts the user to enter the limit of the array and reads the input as an integer.
  • It creates a new array of integers called a with the size of the limit input by the user.
  • It then prompts the user to enter the elements of the array, and reads each element as an integer and stores it in the corresponding index of the array.
  • It initializes max and min variables to the first element of the array.
  • It then iterates over the elements of the array using a for loop and updates the values of max and min if the current element is greater than max or smaller than min, respectively.
  • Finally, it prints the values of max and min.

Note: It's a good practice to close the Scanner object after use to avoid memory leaks. However, it's not required in this program as the Scanner object is only used within the main method and will be automatically garbage collected after the program ends.

Source Code

import java.util.Scanner;
class Array_Max_Min
{
	public static void main(String[] args)
	{   
		Scanner input =new Scanner(System.in);
		System.out.print("Enter the Array Limit :");
		int l =input.nextInt();
		int [] a =new int[l];
		int max=0,min=0;
		for(int i=0;i<l;i++)
		{
			System.out.printf("Element of a[%d] :",i);
			a[i]=input.nextInt();
		}		
		max=a[0];
		min=a[0];
		for(int i=0;i<l;i++)
		{
			if(max<a[i])
				max=a[i];
			if(min>a[i])
				min=a[i];
		}
		System.out.println("Maximum Element of Array : "+max);
		System.out.println("Minimum Element of Array : "+min);
    }
}

Output

Enter the Array Limit :5
Element of a[0] :23
Element of a[1] :4
Element of a[2] :32
Element of a[3] :5
Element of a[4] :75
Maximum Element of Array : 75
Minimum Element of Array : 4

Example Programs