C language only: Write a program that finds the two largest values in an array o
ID: 3804542 • Letter: C
Question
C language only: 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 19 57 2 8 3 1 9 4 Maximum value 9 Second largest value aExplanation / Answer
#include <stdio.h>
int main(void)
{
int i,n,a[20],max = 0;
int secondMax = 0;
int flag = 0;
printf("Enter the number of elements of array :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]); //input n numbers
}
for(i=0;i<n;i++)
{
if(a[i]>max)
max = a[i];
}
printf(" The largest number = %d",max); // max value
for(i=0;i<n;i++)
{
if(a[i] == max) //skip if number is equal to max
i++;
else;
if(a[i]>secondMax && secondMax < max) // find second max ,second max should be less than max
secondMax = a[i];
}
for(i=0;i<n;i++)
{
if(a[i] != max) //check if all numbers are equal , equal to max
{
flag = 1;
break;
}
}
if(flag == 0)
printf(" All values are equal");
else
printf(" The second largest number = %d",secondMax);
return 0;
}
Output:
Enter the number of elements of array : 10
1 9 5 7 2 8 3 1 9 4
The largest number = 9
The second largest number = 8
Enter the number of elements of array : 10
2 2 2 2 2 2 2 2 2 2
The largest number = 2
All values are equal
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.