Minimum and Maximum Value in Array
In this post, we will discuss a simple Java program to find the minimum and maximum values in an array. This program uses straightforward logic to traverse the array, comparing each element to identify the smallest and largest numbers. Let's break it down step-by-step.
import java.util.*;
public class hello(){
public static void main(String args[]){
int n=sc.nextInt();
int arr[]=new int[n];
int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
if(arr[i]<min){
min=arr[i];
}
if(arr[i]>max){
max=arr[i];
}
}
System.out.print(min+" "+max);
}
}
How This Program Works
Input Array Size
The program first reads the size of the array,
n, from the user.Initialize the Array:
An array of size
nis created to store the integers.Set Initial Min and Max:
Integer.MAX_VALUEis the largest value anintcan hold (2^31 - 1). This ensures that any number in the array will be smaller.Integer.MIN_VALUEis the smallest value anintcan hold (-2^31). This ensures that any number in the array will be larger.
Iterate Through the Array: The program loops through all elements in the array using:
Each element is read and stored in the array. During this loop:
- If the current element is smaller than
min, the program updatesmin. - If the current element is larger than
max, the program updatesmax.
- If the current element is smaller than
Print Results: Once the loop finishes, the smallest (
min) and largest (max) numbers in the array are printed:
Example Input and Output
Input:
Process:
- Array elements: [3, 1, 9, 2, 6]
minstarts atInteger.MAX_VALUEand is updated to 3 → 1 (smallest so far).maxstarts atInteger.MIN_VALUEand is updated to 3 → 9 (largest so far).
Output:
Key Points
- Efficiency:
- The program only loops through the array once, making it efficient with a time complexity of O(n).
- Edge Cases:
- If all numbers in the array are the same, both
minandmaxwill have that value. - For an empty array (if
n == 0), the program would fail as no inputs would be read. You can add a check for this case.
- If all numbers in the array are the same, both
Improvements
To make this program more robust, you can:
- Validate the input size
nto ensure it's greater than 0. - Use exception handling to catch invalid inputs.
No comments:
Post a Comment