The following example is the most basic one using structure arrays which are passed to functions. There are no pointers explicitly used or dereferenced within the example. The notation for accessing the structure array is the basic one we have used from the beginning of the Programming I course.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 |
/** * File: struct_students.c * Author: Risto Heinsar * Created: 10.01.2021 * Last edit: 13.02.2024 * * Description: Collects student data and finds the best student. * Compile using --std=c99 or later. */ #include <stdio.h> #include <stdlib.h> #define LEN_NAME 32 #define MAX_STUDENTS 8 typedef struct { char name[LEN_NAME]; float avgGrade; } student; int GetStudentCount(int min, int max); void ReadStudents(student pupils[], int n); int FindBestStudentIndex(student pupils[], int n); int main(void) { student students[MAX_STUDENTS]; /* Get the number of students and store it into memory */ int numOfStudents = GetStudentCount(1, MAX_STUDENTS); ReadStudents(students, numOfStudents); /* Get the best sudent ID */ int bestStudentId = FindBestStudentIndex(students, numOfStudents); printf("The best student is: %s with a grade of %.2f\n", students[bestStudentId].name, students[bestStudentId].avgGrade); return EXIT_SUCCESS; } /** * Description: Reads the number of students, loops until input within allowed * range. * * Parameters: min - lower bound, inclusive * max - upper bound, inclusive * Return: none */ int GetStudentCount(int min, int max) { int num; do { printf("Enter number of students (%d .. %d): ", min, max); scanf("%d", &num); } while (num < min || num > max); return num; } /** * Description: Reads students information (name, grade) * * Parameters: pupils - student array to be populated * n - number of students * Return: none */ void ReadStudents(student pupils[], int n) { for (int i = 0; i < n; i++) { printf("Enter student's name and average grade (%d / %d)\n", i + 1, n); scanf("%s %f", pupils[i].name, &pupils[i].avgGrade); } } /** * Description: Find the index of the student with the highest grade. Assumes * only one maximum. * * Parameters: pupils - student array to be populated * n - number of students * Return: index of the student with the highest grade */ int FindBestStudentIndex(student pupils[], int n) { int bestId = 0; for (int i = 1; i < n; i++) { if (pupils[bestId].avgGrade < pupils[i].avgGrade) { bestId = i; } } return bestId; } |