Java program to find maximum and minimum element in an Array

Today we will see how to find the maximum and minimum element in an array in Java.

For this purpose, we will use two variables max and min and then compare them with each element and replace them with the appropriate number so as to get the maximum and minimum value at last.

Here is how the code will look like:

import java.util.*;
public class test
{
  public static void main(String[] args)
  {
       
       Scanner sc=new Scanner(System.in);
       int arr[]=new int[10];
       System.out.println("Enter elements in array");
       int min=Integer.MAX_VALUE;
       int max=Integer.MIN_VALUE;
       for(int i=0;i<=9;i++)
       {
    	   arr[i]=sc.nextInt();
    	   if(arr[i]<min)
    		   {
    		   min=arr[i];
    		   }
    	   if(arr[i]>max)
    	   {
    		   max=arr[i];
    	   }
       }
       System.out.println("Maximum element is "+max);
       System.out.println("Minimum element is "+min);
       
       
  }
}

Now if you look at the code you will see I have initialized min and max to MAXIMUM and MINUMUM integer values respectively.

This is because we cannot initialize them to 0 because then the minimum element will be 0 itself if the array contains all positive integers.

The code when executed will give the following result:

Enter elements in array
12
13
15
43
67
55
99
16
19
2
Maximum element is 99
Minimum element is 2

Hope this helped you out.

Have a nice day ahead.

Also Read:

Aadding days to date in C++

How to Rotate a Matrix in C++ ( Both Clockwise and Anticlockwise )

Finding out the next greater number from the same set of digits using C++

 

Leave a Reply

Your email address will not be published. Required fields are marked *