I'm supposed to write a program that outputs the average from an unknown amount of inputs. For that I will use a sentinel value (-1) to end the while loop. Also, the program will use a for loop that will call the function four times. Each time I will enter a new set of number and each time the average will be printed.
Code:
#include <stdio.h>
void calculateAverage (void);
int main(void) {
int i;
float average;
for (i = 1; i <= 4; ++i) {
calculateAverage();
}
return 0;
}
void calculateAverage (void) {
int sumofGrades = 0;
int numberofGrades = 0;
float average = 0.0;
int grade = 0;
while(grade != -1 && grade >= 0 && grade <= 100) {
if(grade != -1) {
numberofGrades++;
sumofGrades += grade;
}
printf("Enter grades and type -1 to stop: \n");
scanf("%d", &grade);
}
average = (float)sumofGrades / numberofGrades;
printf("The average is %.2f\n", average);
}
The output that I get is this:
Enter grades and type -1 to stop:
3 5 6 8 -1
Enter grades and type -1 to stop:
Enter grades and type -1 to stop:
Enter grades and type -1 to stop:
Enter grades and type -1 to stop:
The average is 4.40
Enter grades and type -1 to stop: