How can I return the second highest value in an array? (C Programming) This is t
ID: 3802664 • Letter: H
Question
How can I return the second highest value in an array? (C Programming)
This is the input. Column one is the "category", two is the "id", and three is the "scores"
for example, if I have this input:
A 21 1171.00
S 19 1046.50
S 11 1094.20
S 15 638.10
C 6 696.70
A 27 756.50
C 8 522.30
C 32 578.00
A 14 601.10
C 2 344.00
my output needs to look like:
A: 21 1171.00
C: 6 696.70
C: 32 578.00
S: 11 1094.20
S: 19 1046.50
This is a sample of what I have:
int findMax (char key, char category[], float scores[], int n);
int main(){
m = findMax('A', category, scores, n);
printf("%c: %d %.2f ",category[m],id[m],scores[m]);
m = findMax('C', category, scores, n);
printf("%c: %d %.2f ",category[m],id[m],scores[m]);
m = findMax('C', category, scores, n);
printf("%c: %d %.2f ",category[m],id[m],scores[m]);
m = findMax('S', category, scores, n);
printf("%c: %d %.2f ",category[m],id[m],scores[m]);
m = findMax('S', category, scores, n);
printf("%c: %d %.2f ",category[m],id[m],scores[m]);
}
int findMax(char key, char category[], float scores[], int n) {
int i, max=0, loc;
for (i=0; i if (key == category[i]){
if (scores[i] > max){
max = scores[i];
loc = i;
}
}
}
return loc;
}
My codes output returns this:
A: 21 1171.00
C: 6 696.70
C: 6 696.70
S: 11 1094.20
S: 11 1094.20
How can I return the second highest value for the 'C' and 'S' category?
Explanation / Answer
Ans
You are calculating higest score value not second highest...
and if you want to calculate second higest then program is:
#include<stdio.h>
int findMax (char key,char category[],float score[], int n);
int main(){
char category[]={'A','S','S','S','C','A','C','C','A','C'};
float scores[]={1171.00,1046.00,1094.00,638.00,696.00,756.00,522.00,578.00,601.00,344.00};
int id[]={21,19,11,15,6,27,8,32,14,2};
int m;
m=findMax('A',category,scores,n);
printf("%c: %d %.2f ",category[m],id[m],scores[m]);
m = findMax('C', category, scores, n);
printf("%c: %d %.2f ",category[m],id[m],scores[m]);
m = findMax('C', category, scores, n);
printf("%c: %d %.2f ",category[m],id[m],scores[m]);
m = findMax('S', category, scores, n);
printf("%c: %d %.2f ",category[m],id[m],scores[m]);
m = findMax('S', category, scores, n);
printf("%c: %d %.2f ",category[m],id[m],scores[m]);
}
int findMax(char key, char category[], float scores[], int n) {
int i, loc=0;
float first=0.0;
float second=0.0;
float sec=0.0;
for (i=0;i<10;i++){
sec=second;
if (key==category[i]){
first=scores[i];
second=scores[i];
if(first<scores[i]){
second = first;
first = scores[i];
}
else if(sec<scores[i])
{
second=scores[i];
loc=i;
sec=second;
}
else{
}
}
}
return loc;
}
// n is of no use
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.