Read n students, each with a name and a CGPA, and print the name and CGPA (with 2 decimals) of the student with the highest CGPA. If two have the same CGPA, print the one that came first.
What to build
An array of structs and a search through it.
Requirements
- Read the students.
- Print the name and CGPA of the first student with the highest CGPA.
Input
The first line has n (1 ≤ n ≤ 50). Each of the next n lines has a name (one word, up to 20 letters) and a CGPA.
Output
name cgpa, for example Nadia 3.92.
Constraints
n is from 1 to 50. Names have up to 20 letters.
Example
Input:
3
Rahim 3.45
Nadia 3.92
Karim 3.10
Output:
Nadia 3.92
Why it works
Each student stays together as one struct, so remembering the position of the best one gives both the name and the CGPA.
Examples
Example 1 · Input
3 Rahim 3.45 Nadia 3.92 Karim 3.10
Expected output
Nadia 3.92
Example 2 · Input
1 Ayesha 4.00
Expected output
Ayesha 4.00
Hints
Hint 1
Define struct student { char name[21]; double cgpa; };
Hint 2
Read each name with %20s and each CGPA with %lf.
Hint 3
Keep the index of the best one; on a tie the first one stays.
Solution
Show one correct solution (try it yourself first)
#include <stdio.h>
struct student {
char name[21];
double cgpa;
};
int main(void) {
int n;
struct student s[50];
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%20s %lf", s[i].name, &s[i].cgpa);
int best = 0;
for (int i = 1; i < n; i++)
if (s[i].cgpa > s[best].cgpa) best = i;
printf("%s %.2f\n", s[best].name, s[best].cgpa);
return 0;
}