Challenge: Best Student
Completed
Read n, then n lines each with a name (one word) and a score. Store them in a vector of structs and print the name and score of the student with the highest score (the first one if there is a tie), then the class average with 1 decimal place.
Input
n, then n lines: name score.
Output
Best: Sara 92 Average: 81.7
Example
Input
3 Ali 75 Sara 92 Tom 78
Output
Best: Sara 92 Average: 81.7
Editor
C++
Hints
struct Student { string name; int score; };
Read into each item: cin >> s.name >> s.score;
Use > (not >=) so the first of a tie wins.
Solution explanation
Each struct keeps a name together with its score, so when you find the best score you also have the right name.
Show solution
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
using namespace std;
struct Student {
string name;
int score;
};
int main() {
int n;
cin >> n;
vector<Student> students(n);
double total = 0;
for (Student& s : students) {
cin >> s.name >> s.score;
total += s.score;
}
Student best = students[0];
for (const Student& s : students) {
if (s.score > best.score) {
best = s;
}
}
cout << "Best: " << best.name << " " << best.score << "\n";
cout << fixed << setprecision(1) << "Average: " << total / n << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module