How to find top two max numbers in the given array
public class TopTwoMaxNumbersInArray {
public static void main(String args[]) {
int[] numbers = {23,34,12,7,90,37,45,52};
int maxFirst = 0;
int maxSecond = 0;
for (int n : numbers) {
if (maxFirst < n) {
maxSecond = maxFirst;
maxFirst = n;
}
else if (maxSecond < n) {
maxSecond = n;
}
}
System.out.println("The first max number is "+ maxFirst);
System.out.println("The second max number is "+ maxSecond);
}
}
Ouput:
The first max number is 90
The second max number is 52
public class TopTwoMaxNumbersInArray {
public static void main(String args[]) {
int[] numbers = {23,34,12,7,90,37,45,52};
int maxFirst = 0;
int maxSecond = 0;
for (int n : numbers) {
if (maxFirst < n) {
maxSecond = maxFirst;
maxFirst = n;
}
else if (maxSecond < n) {
maxSecond = n;
}
}
System.out.println("The first max number is "+ maxFirst);
System.out.println("The second max number is "+ maxSecond);
}
}
Ouput:
The first max number is 90
The second max number is 52
No comments:
Post a Comment