#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Student {
char name[15];
char lastname[50];
int age;
} student;
int findYoungest(struct Student students[10], int length) {
int currentYoungestIndex = 0;
for (int i = 0; i < length; i++) {
if (students[currentYoungestIndex].age > students[i].age) {
currentYoungestIndex = i;
}
}
return currentYoungestIndex;
}
int findOldest(struct Student students[10], int length) {
int currentOldestIndex = 0;
for (int i = 1; i < length; i++) {
if (students[currentOldestIndex].age < students[i].age) {
currentOldestIndex = i;
}
}
return currentOldestIndex;
}
void printStudentInformation(struct Student students[10], int countOfStudents) {
if(countOfStudents <= 0) {
printf("No students were given\n");
}
printf("Count: %i\n", countOfStudents);
for (int i = 0; i < countOfStudents; ++i) {
printf("Name = %s%s, Age = %d\n", students[i].name, students[i].lastname, students[i].age);
}
printf("Youngest: %s%s\n",
students[findYoungest(students, countOfStudents)].name,
students[findYoungest(students, countOfStudents)].lastname);
printf("Oldest: %s%s\n",
students[findOldest(students, countOfStudents)].name,
students[findOldest(students, countOfStudents)].lastname);
}
int main() {
char name[50];
char lastname[50];
int age;
char stop[] = "stop";
int wroteStop = 1;
int countOfStudents = 0;
student * students = NULL;
while (wroteStop) {
scanf("%s", name);
fgets(lastname, 49, stdin);
name[strcspn(name, "\n")] = 0;
lastname[strcspn(lastname, "\n")] = 0;
if (strcmp(name, stop) != 0) {
scanf("%i", &age);
// Create dynamic array
if (!students) {
students = (student *) malloc(sizeof(student *));
} else {
students = (student *) realloc(students, sizeof(countOfStudents + 1));
}
// Add student to list.
strcpy(students[countOfStudents].name, name);
strcpy(students[countOfStudents].lastname, lastname);
students[countOfStudents].age = age;
countOfStudents++;
} else {
wroteStop = 0;
}
}
// Print student information
printStudentInformation(students, countOfStudents - 1);
free(students);
students = NULL;
return 0;
}
Example input:
Erin Smith
10
Matthew Berg
90
Alexandria Garcia
60
Michelle Lewis
85
Amanda Best
34
Michelle Cook
47
Todd Vazquez
13
Erica Moss
50
Sarah Holder
41
Charles Vincent Jr.
29
Joshua Rivera
25
Katherine Peters
56
Natasha Lee
32
Emily Carter
79
Bryan Ingram
87
Gavin Lewis
53
Richard Ellis
51
Nicole Payne
55
Brian Cantrell
20
William Jackson
16
stop
Timed out while waiting for your program to exit. The program might be waiting on input or have an endless loop."
The user types in: Firstname, Surname and Age.
This is appended to a list, which is later iterated through so that we get very student in the list and the youngest/oldest student in the list. If the user types "stop", the output-function named printStudentInformation()
is executed