Java program to find the maximum and minimum value of an array. code example
Example 1: Java program to find maximum and minimum number without using array
// Java program to find maximum and minimum number without using array
import java.util.Scanner;
public class MaximumMinimumWithoutArray
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter total number: ");
int numbers = sc.nextInt();
int maximum = Integer.MIN_VALUE;
int minimum = Integer.MAX_VALUE;
System.out.println("Please enter " + numbers + " numbers.");
for(int a = 0; a < numbers; a++)
{
int current = sc.nextInt();
if(current > maximum)
{
maximum = current;
}
if(current < minimum)
{
minimum = current;
}
}
System.out.println("largest of " + numbers + " numbers is: " + maximum);
System.out.println("smallest of " + numbers + " numbers is: " + minimum);
sc.close();
}
}
Example 2: Find minimum and maximum values in a java array
// Find minimum and maximum values in a java array
public class MaxMinValueInArray
{
public static void main(String[] args)
{
int[] arrNumber = new int[]{50, 150, 250, 500, 160, 530};
int maximum = maxNumber(arrNumber);
System.out.println("Maximum value : " + maximum);
// calling min function java
int minimum = minNumber(arrNumber);
System.out.println("Minimum value : " + minimum);
}
// java find max in array
public static int maxNumber(int[] arr)
{
int maximumValue = arr[0];
for(int a = 1; a < arr.length; a++)
{
if(arr[a] > maximumValue)
{
maximumValue = arr[a];
}
}
return maximumValue;
}
// java min of array
public static int minNumber(int[] arr)
{
int minimumValue = arr[0];
// find minimum value in array java
for(int a = 1; a < arr.length; a++)
{
if(arr[a] < minimumValue)
{
minimumValue = arr[a];
}
}
return minimumValue;
}
}
Example 3: finding min and max from given number in java
Scanner input = new Scanner(System.in);
// Minimum And Maximum
int count = 0;
int min = 0;
int max = 0;
boolean bugSolved = true;
/* or we can use :
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
*/
while (true){
int cnt = count++;
System.out.print("Enter Number #"+(cnt+1)+": ");
boolean isValid = input.hasNextInt();
if(isValid){
int num = input.nextInt();
/* if (bugSolved){
bugSolved = false;
min = num;
max = num;
}
boolean (bugSolved) at the top, if you use
int min = Integer.MAX_VALUE and int max =
Integer.MIN_VALUE */
if (num < min) {
min = num;
}else if (num > max){
max = num;
}
}else{
System.out.println("Invalid input..");
break;
}
input.nextLine();
}
System.out.println("Min Number : " + min);
System.out.println("Max Number : " + max);