Add answers for problem 2

This commit is contained in:
Myles Busig 2024-10-30 00:05:20 -07:00
parent 49a7aeb1f8
commit 6cdb4014d0
3 changed files with 52 additions and 0 deletions

8
include/p2.h Normal file
View File

@ -0,0 +1,8 @@
#ifndef P2_H
#define P2_H
void find_avg_min_max(double* arr, int size,
double* out_avg, double* out_min, double* out_max);
#endif

View File

@ -1,6 +1,7 @@
#include <stdio.h>
#include "p1.h"
#include "p2.h"
int main(void) {
// Problem 1
@ -8,6 +9,17 @@ int main(void) {
printf("Number of alphanumeric characters in \"Hello World!!\": %d\n", num_alphanum);
// Problem 2
double arr[8] = {
2.5, 4.3, 8.1, -7.4, 2.0, 1.0, 3.0, 4.0
};
double avg = 0;
double min = 0;
double max = 0;
find_avg_min_max(arr, 8, &avg, &min, &max);
printf("Average: %.2lf, Min: %.2lf, Max: %.2lf\n", avg, min, max);
return 0;
}

32
src/p2.c Normal file
View File

@ -0,0 +1,32 @@
#include "p2.h"
void find_avg_min_max(double* arr, int size,
double* out_avg, double* out_min, double* out_max) {
// If there are no elements in the array, attempting to access the first
// element to initialize min and max will access memory outside the bounds
// of the array. Instead, we will return early.
if (size <= 0) {
return;
}
double sum = 0;
double min = arr[0];
double max = arr[0];
for (int i = 0; i < size; ++i) {
sum += arr[i];
if (arr[i] < min) {
min = arr[i];
}
if (arr[i] > max) {
max = arr[i];
}
}
*out_avg = sum / size;
*out_min = min;
*out_max = max;
}