Add answers for problem 2
This commit is contained in:
parent
49a7aeb1f8
commit
6cdb4014d0
8
include/p2.h
Normal file
8
include/p2.h
Normal 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
|
||||||
|
|
||||||
12
src/main.c
12
src/main.c
@ -1,6 +1,7 @@
|
|||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
|
||||||
#include "p1.h"
|
#include "p1.h"
|
||||||
|
#include "p2.h"
|
||||||
|
|
||||||
int main(void) {
|
int main(void) {
|
||||||
// Problem 1
|
// Problem 1
|
||||||
@ -8,6 +9,17 @@ int main(void) {
|
|||||||
printf("Number of alphanumeric characters in \"Hello World!!\": %d\n", num_alphanum);
|
printf("Number of alphanumeric characters in \"Hello World!!\": %d\n", num_alphanum);
|
||||||
|
|
||||||
// Problem 2
|
// 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;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
32
src/p2.c
Normal file
32
src/p2.c
Normal 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;
|
||||||
|
}
|
||||||
|
|
||||||
Loading…
x
Reference in New Issue
Block a user