Home » Java programs

Java program to get minimum and maximum elements from the array

In this Java program, we are going to read an array with N elements and find the minimum (smallest) and maximum (largest) elements from given array elements.
Submitted by IncludeHelp, on October 28, 2017

Given an array, and we have to find/get the minimum and maximum elements from it using Java program.

Here, we are taking N number of elements and finding the smallest (minimum) and largest (maximum) numbers among them.

We create a class named "MinMaxInArray" which has some methods,

getMax - this method will take an array as an argument and returns an integer value, which is the maximum (largest) element in the given array.

getMin - this method will take an array as an argument and returns an integer value, which is the minimum (smallest) element in the given array.

Then, we created another class named "Main" which is the main program, containing the code to read array, finding minimum and maximum elements by calling methods of "MinMaxInArray" class.

import java.util.Scanner;

class MinMaxInArray 
{
	//method to get maximum number from array elements
	int getMax(int[]inputArray)
	{
		int maxValue=inputArray[0];

		for(int i=1;i<inputArray.length;i++)
		{
			if(inputArray[i]>maxValue)
			{
				maxValue=inputArray[i];
			}
		}
		return maxValue;
	}

	//method to get minimum number from array elements
	int getMin(int[]inputArray)
	{
		int minValue=inputArray[0];

		for(int i=1;i<inputArray.length;i++)
		{
			if(inputArray[i]<minValue)
			{
				minValue=inputArray[i];
			}
		}
		return minValue;
	}
}

public class Main
{
	public static void main(String[] args)
	{
		int n;

		// create object of scanner.
		Scanner sc = new Scanner(System.in);

		// you have to enter number here.
		System.out.print("Enter number of elements you wants to enter :" );

		// read entered number and store it in "n".
		n=sc.nextInt();

		int arr[]=new int[n];

		for(int i=0;i<arr.length;i++)
		{
			System.out.print("Enter ["+(i+1)+"] element :" );
			arr[i]=sc.nextInt();
		}

		MinMaxInArray mm=new MinMaxInArray();

		System.out.print("Maximum value is :" +mm.getMax(arr));
		System.out.print("Minimum value is :" +mm.getMin(arr));
	}
}

Output

Enter number of elements you wants to enter : 5
Enter[1] element : 12
Enter[2] element : 65
Enter[3] element : 25
Enter[4] element : 5
Enter[5] element : 60

Maximum Value is : 65
Minimum Value is : 5







Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.