Code:
#include <stdio.h>
int ReadRes(int n, double *r, double *v); // The function that will read the resistance and voltage. *r and *v are pointers while n is the resistor #.
void MinMaxAvg(double x[], int n, double *min, double *max, double *avg); // The function that will calculate the quantities for each input as the pointers included in this function will end up being used to calculate the outputs.
int main () {
double R, V, I_min, P_min, V_min, I_max, P, P_max, V_max, I_avg, P_avg, V_avg;
double I; // Current values
int n; // # of elements in array
/* R and V are the resistance and voltage values to be entered by the user.
The other declared double variables will be used to calculate the min, max, and avg for current and power. */
for (n = 1; n <= 20; n++) {
printf(
"Enter R and V for resistor %d: ", n);
ReadRes(n, &R, &V);
// Calculate min, max, and average values for current
MinMaxAvg(&V, n, &V_min, &V_max, &V_avg);
I = V / R;
MinMaxAvg(&I, n, &I_min, &I_max, &I_avg);
P = V * I;
MinMaxAvg(&P, n, &P_min, &P_max, &P_avg);
printf(" Voltage Current Power\n");
printf("MIN %.4lf %.4lf %.4lf\n", V_min, I_min, P_min);
printf("MAX %.4lf %.4lf %.4lf\n", V_max, I_max, P_max);
printf("AVG %.4lf %.4lf %.4lf\n", V_avg, I_avg, P_avg);
}
return 0;
}
int ReadRes(int n, double *r, double *v) {
int scanfRetVal = scanf("%lf %lf", *r, *v);
while (1) {
if (*r > 0) {
if (scanfRetVal < 2) {
return -1;
}
else
if (scanfRetVal == EOF) {
return 0; // Indicates no valid data read
break;
}
else
return 1;
break;
}
else
printf("Error: R must be greater than 0\n");
}
}
void MinMaxAvg(double x[], int n, double *min, double *max, double *avg) {
int i;
double sum;
sum = 0;
*min = x[0];
for (i = 0; i < n; i++) {
if (x[i] < *min)
*min = x[i];
}
*max = x[0];
for (i = 0; i < n; i++) {
if (x[i] > *max)
*max = x[i];
}
for (i = 0; i < n; i++) {
sum += x[i];
}
*avg = sum / n;
}