Given an array of numbers, find the maximum and minimum element in the array ?
***
Given an array of numbers, find the maximum and minimum element in the array.
Input
[54, 546, 548, 60]
Output
548 54
package
InterviewProgram;
public class MaxMinElement {
public static void main(String[] args) {
int[] arr = {54, 546, 548, 60};
System.out.println("input = {54, 546, 548, 60}");
int max = arr[0]; // Initialize max with the first element of the array
int min = arr[0]; // Initialize min with the first element of the array
// Iterate through the array to find the maximum and minimum
elements
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
}
// Print the results
System.out.println("Maximum element: " + max);
System.out.println("Minimum element: " + min);
}
}
input = {54, 546, 548, 60}
Maximum element: 548
Minimum element: 54
Explanation:
1.We initialize two variables, max and min, with the first element of the array arr[0].2.We then iterate through the rest of the array starting from index 1.
3.Inside the loop, we compare each element with the current max and min values.
4.If we find an element greater than the current max, we update the max value.
5.If we find an element smaller than the current min, we update the min value.
6.After iterating through the whole array, we have found the maximum and minimum elements.
7.We print the results as Maximum element: 548 and Minimum element: 54 in this case.
Comments
Post a Comment