I'm building a program that uses a struct to record student records. A task is to create a function (findOldest
) to compare each record and find the oldest student.
This is my code so far:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char name[20];
char surname[20];
char UUN[6];
char department[4];
char gender;
int age;
} student;
void printStudent(student s) {
printf("Name: %s %s\n", s.name, s.surname);
printf("UUN: %s\n", s.UUN);
printf("Department: %s\n", s.department);
printf("Gender: %c\n", s.gender);
printf("Age: %d\n", s.age);
}
student findOldest ( student *studentarr, int len ) {
int age = 0;
int i;
for ( i = 0; i < len; i++ ) {
if ( age <= studentarr[i].age ) {
age = studentarr[i].age;
}
}
}
int main(void) {
int i, length;
student studentarr[6] = {
{ "John", "Bishop", "s1234", "Inf", 'm', 18 },
{ "Lady", "Cook", "s2345", "Eng", 'f', 21 },
{ "James", "Jackson", "s3456", "Eng", 'm', 17 },
};
for ( i = 3; i < 6; i++ ) {
printf("Enter student %d details:\n", i+1);
printf("Forename: ");
scanf("%s", studentarr[i].name);
printf("Surname: ");
scanf("%s", studentarr[i].surname);
printf("UUN: ");
scanf("%s", studentarr[i].UUN);
printf("Department: ");
scanf("%s", studentarr[i].department);
printf("Gender: ");
scanf(" %c", &studentarr[i].gender);
printf("Age: ");
scanf("%d", &studentarr[i].age);
printf("\n\n");
}
for ( i = 0; i < 6; i++ ) {
printf("Student %d\n", i+1);
printStudent(studentarr[i]);
printf("\n\n");
}
length = sizeof(studentarr) / sizeof(studentarr[0]);
printf("Size of studentarr is %d.\n", length);
return 0;
}
The task was for the program to define the first three elements of studentarr, as done, and have the user define the last three, again as done. Then call the function findOldest. My problem is creating findOldest, I've made an attempt but I'm fairly sure it's wrong.
Trying to compile as is gives the warning;
studentDB2.c:30:1: warning: control reaches end of non-void function
[-Wreturn-type]
}
^
1 warning generated.
Edit: Okay the function has been changed too;
student findOldest ( student *studentarr, int len ) {
int age = 0, oldest_index = 0;
int i;
for ( i = 0; i < len; i++ ) {
if ( age <= studentarr[i].age ) {
age = studentarr[i].age;
oldest_index = i;
}
}
return studentarr[oldest_index];
}
How do I use a printf statement at the end of main to say, the oldest student is (Student 4, for example) and is 19 (again example) years old?
Edit: I've tried this
printf("The oldest student is %d years old.\n", findOldest(&studentarr[6], length).age);
It's calling the function, and should return studentarr[1], as this is the index with the highest age (21 years). Instead the compiler is returning;
The oldest student is 1297237332 years old.
What is the problem?