Write a program that finds the two largest values in an array of integers. In th
ID: 3802711 • Letter: W
Question
Write a program that finds the two largest values in an array of integers. In this program, the largest value and the second largest value cannot be the same, even if the largest value occurs multiple times.
Notice, in the sample below, the value=9 appears twice. It should not be considered as largest and second largest. It’s only counted once.
In the sample below, all the values are equal. The program recognizes that there are no two distinct values and prints a message indicating so.
Arrays data 1 9 5 7 2 8 3 1 9 4 Maximum value 9 Second largest value 8Explanation / Answer
HI Friend, You have not mentioned about any programming language.
Please try to mention all details.
I have implemented in Java.
public class TwoMaxNumbers {
public static void printTwoMaxNumbers(int[] nums){
int maxOne = 0;
int maxTwo = 0;
for(int i=0; i<nums.length; i++){
if(i == 0){ // initializing with first number
maxOne = nums[i];
maxTwo = nums[i];
}else{
if(maxOne < nums[i]){
maxTwo = maxOne;
maxOne = nums[i];
}else if(maxTwo < nums[i] && maxOne != nums[i]){
maxTwo = nums[i];
}
}
}
if(maxOne == maxTwo){
System.out.println("Maximum value: "+maxOne);
System.out.println("All the values are equal");
}else{
System.out.println("Maximum value: "+maxOne);
System.out.println("Second largest value: "+maxTwo);
}
}
public static void main(String a[]){
int num[] = {5,34,78,2,45,1,99,23};
printTwoMaxNumbers(num);
}
}
/*
Sample run:
Maximum value: 99
Second largest value: 78
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.