Add problem 8 solution

This commit is contained in:
Myles Busig 2024-10-31 00:54:11 -07:00
parent feab097a60
commit 56ac8c91f8
3 changed files with 76 additions and 0 deletions

18
include/p8.h Normal file
View File

@ -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

View File

@ -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;
}

40
src/p8.c Normal file
View File

@ -0,0 +1,40 @@
#include "p8.h"
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
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;
}