From a08593f53d5b16affb6e0bb1f7276f4520de2ae7 Mon Sep 17 00:00:00 2001 From: Madeline Busig Date: Thu, 31 Oct 2024 00:54:11 -0700 Subject: [PATCH] Add problem 8 solution --- include/p8.h | 18 ++++++++++++++++++ src/main.c | 18 ++++++++++++++++++ src/p8.c | 40 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 include/p8.h create mode 100644 src/p8.c diff --git a/include/p8.h b/include/p8.h new file mode 100644 index 0000000..74e2b79 --- /dev/null +++ b/include/p8.h @@ -0,0 +1,18 @@ +#ifndef P8_H +#define P8_H + +// 8.a + +typedef struct { + int id; + char first_name[16]; + char last_name[16]; + double gpa; +} Student; + +void prompt_student_info(Student* out_student); +void print_student(Student* student); +double compute_average_gpa(Student* students, int num_students); + +#endif + diff --git a/src/main.c b/src/main.c index 7720195..7576133 100644 --- a/src/main.c +++ b/src/main.c @@ -7,6 +7,7 @@ #include "p5.h" #include "p6.h" #include "p7.h" +#include "p8.h" void print_int_arr(int* arr, int size) { for (int i = 0; i < size; ++i) { @@ -77,6 +78,23 @@ int main(void) { reverse_string(p7_str); printf("\"%s\"\n", p7_str); + // Problem 8 + printf("Problem 8:\n"); + + Student students[5]; + + for (int i = 0; i < 5; ++i) { + prompt_student_info(&students[i]); + } + + for (int i = 0; i < 5; ++i) { + print_student(&students[i]); + } + + double average_gpa = compute_average_gpa(students, 5); + + printf("Average GPA: %.2lf\n", average_gpa); + return 0; } diff --git a/src/p8.c b/src/p8.c new file mode 100644 index 0000000..8c05d74 --- /dev/null +++ b/src/p8.c @@ -0,0 +1,40 @@ +#include "p8.h" + +#define _CRT_SECURE_NO_WARNINGS + +#include + +void prompt_student_info(Student* out_student) { + printf("Enter student ID: "); + scanf("%d", &out_student->id); + + printf("Enter student first name: "); + // Our array can only hold 16 characters including the null terminator, + // so we can only read 15 non-null characters. Consider what happens + // to any remaining characters if the user enters a string longer than + // 15 characters. + scanf("%15s", out_student->first_name); + + printf("Enter student last name: "); + // Same as first name + scanf("%15s", out_student->last_name); + + printf("Enter student GPA: "); + scanf("%lf", &out_student->gpa); +} + +void print_student(Student* student) { + printf("%8d%16s%16s%8.2lf\n", student->id, student->first_name, + student->last_name, student->gpa); +} + +double compute_average_gpa(Student* students, int num_students) { + double gpa_sum = 0.0; + + for (int i = 0; i < num_students; ++i) { + gpa_sum += students[i].gpa; + } + + return gpa_sum / num_students; +} +