In: Computer Science
Problem: Construct a C program that will make use of user-defined functions, the do/while loop, the for loop, and selection. Using a do/while loop, your program will ask/prompt the user to enter in a positive value representing the number of values they wish to have processed by the program or a value to quit/exit. If the user enters a 0 or a negative number the program should exit with a message to the user indicating they chose to exit. If the user has entered a valid positive number, your program should pass that number to a user defined function. The user-defined function will use a for loop to compute an average value. The function will use the number passed to it to determine how many times it will prompt the user to supply a value. The user may enter in any number value positive, floating-point, or negative. The for loop will continue to prompt the user, calculating the average of the values entered. The function should return the calculated value to the calling function. The calling function using the do/while loop should print out the average and then repeat the process until the user enters the signal to stop as described previously.
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks
#include<stdio.h>
//method to read n numbers and find average
float processValues(int n){
float sum=0, input;
//looping for n times
for(int i=1;i<=n;i++){
//asking and reading a value
printf("Enter number #%d: ",i);
scanf("%f",&input);
//adding to sum
sum+=input;
}
//finding and returning average
float avg=sum/n;
return avg;
}
int main(){
int n;
//looping
do{
//asking, reading number of values
printf("Enter the number of values (0 or negative to quit): ");
scanf("%d",&n);
//checking if value is positive
if(n>0){
//processing values and finding average
float avg=processValues(n);
//displaying average
printf("The average of entered values: %.2f\n",avg);
}
}while(n>0); //loop until n is 0 or negative
//displaying a goodbye message.
printf("You chose to quit. Goodbye!\n");
return 0;
}
/*OUTPUT*/
Enter the number of values (0 or negative to quit): 5
Enter number #1: 11
Enter number #2: 22
Enter number #3: 33
Enter number #4: 44
Enter number #5: 55
The average of entered values: 33.00
Enter the number of values (0 or negative to quit): 3
Enter number #1: 100
Enter number #2: 50
Enter number #3: 25.45
The average of entered values: 58.48
Enter the number of values (0 or negative to quit): 4
Enter number #1: 100
Enter number #2: 100
Enter number #3: 98
Enter number #4: 99.5
The average of entered values: 99.38
Enter the number of values (0 or negative to quit): 0
You chose to quit. Goodbye!