Challenge: The Oldest Person
Completed
Read n, then n people as name age. Store them in an array of structs and print the name of the oldest person (if there is a tie, the first one wins) and the average age with 1 decimal.
Input
n (1 ≤ n ≤ 50), then n lines of a name and an age.
Output
Oldest: NAME Average age: X.X
Example
Input
3 Asha 31 Bo 45 Cy 22
Output
Oldest: Bo Average age: 32.7
Editor
C
Hints
Keep the index of the oldest person so far.
Use > (not >=) so the first one wins a tie.
Solution explanation
One loop reads every person, adds up the ages and tracks who is oldest.
Show solution
#include <stdio.h>
typedef struct {
char name[30];
int age;
} Person;
int main() {
int n;
Person people[50];
scanf("%d", &n);
int total = 0;
int oldest = 0;
for (int i = 0; i < n; i++) {
scanf("%s %d", people[i].name, &people[i].age);
total += people[i].age;
if (people[i].age > people[oldest].age) {
oldest = i;
}
}
printf("Oldest: %s\n", people[oldest].name);
printf("Average age: %.1f\n", (double) total / 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