Java program to find maximum and minimum number in an array
Written by
Java Program to find the maximum and minimum number
In the following question, we are supposed to enter N elements in a dynamic array of size n. After entering into the array, we’ll have to find and print the maximum and minimum element present in the array.
The standard algorithm will be:
- Declare a variable
N
to store the size of the array. - Prompt the user to enter the size of the array and store the input in
N
. - Declare an array of size
N
to store the integer inputs. - Declare 2 variables,
min_element
andmax_element
, to store the minimum and maximum elements, respectively. - Initialize
min_element
andmax_element
with the first element of the array. - Use a loop to iterate over the array, starting from the second element.
- Within the loop, compare each element with
min_element
andmax_element
. If the current element is less thanmin_element
, updatemin_element
to the current element. If the current element is greater thanmax_element
, updatemax_element
to the current element. - After the loop terminates, print the minimum and maximum elements found, along with a message indicating the result.
Java Code:
import java.util.*;
class ArrMinMax {
public static void main() {
Scanner inp = new Scanner(System.in);
System.out.print("\n Enter Size of Array: ");
int n = inp.nextInt();
int i, sum = 0;
int arr[] = new int[n]; //Creating N-size Array
for (i = 0; i < n; i++) { //Entering N numbers in array
System.out.print("\n Enter: ");
arr[i] = inp.nextInt();
}
int max_element = arr[0], min_element = arr[0]; //Initializing with first element.
for (i = 0; i < n; i++) {
if (arr[i] > max_element) { //Checking Maximum element
max_element = arr[i];
}
if (arr[i] < min_element) { //Checking Minimum element
min_element = arr[i];
}
}
//Printing Result
System.out.println("\n Maximum Number: " + max_element);
System.out.println("\n Minimum Number: " + min_element);
}
}
Output:
Enter Size of Array: 6
Enter: 12
Enter: 36
Enter: 5
Enter: 41
Enter: 20
Enter: 36
Maximum Number: 41
Minimum Number: 5