Write a C program that calculates the average of a stream of positive numbers. T
ID: 3761181 • Letter: W
Question
Write a C program that calculates the average of a stream of positive numbers. The user can enter as many positive numbers as they want, and they will indicate that they are finished by entering a negative number. For this program, treat zero as a positive number, i.e., zero counts as a number that goes into the average. Of course, the negative number should not be part of the average. You must use a function to read in the numbers, keep track of the running sum and count, compute the average, and return the average to the main() function. Note that you must use a loop to do this, as you don't know how many numbers the user will enter ahead of time. The main() function should print the average (which was returned from your function), and then ask the user if they want to repeat the entire process. The user should be allowed to repeat the process as many times as they wish. This means you will have a loop in your main() function that instructs the user what to do, calls your average function, reports the result, and finally asks the user if they want to calculate another average for a different set of numbers. Note that your function should have no printf statements. All output must happen in main(). Also, be sure you take the time to think through the pieces and, more importantly, implement in small steps. I suggest you proceed like so: - Get the structure of defining and calling your function down first, with no loops involved. - Fill in the function with a loop that runs while the user enters positive (or zero) numbers. - Modify the loop to keep track of the sum and count, then print the average in the function. - Modify the function to actually return the average. - Modify main() to use another loop to ask the user if they want to repeat the entire calculation. At each step, build your program, fix any errors, test it out, and convince yourself that that piece is correct before moving on.
#include <stdio.h>
double avg();
int main()
{
char answer;
double re;
do {
re = avg();
printf("The avarage of your inputs is: %f ", re);
printf("Do you want to continue? (y/n): ");
scanf(" %c", &answer);
} while (answer == 'y');
return 0;
}
double avg()
{
printf("Your code goes here. ");
return 0;
}
plz i want someone who can help me out with this and send me the full code well organizied. thank you in advance
Explanation / Answer
#include <stdio.h>
double avg(){
int sum = 0,count = 0;
int n = 1;
while(n >= 0){
scanf("%d",&n);
sum += n;
count++;
}
return (double)sum/count;
}
int main()
{
char answer;
double re;
do {
re = avg();
printf("The avarage of your inputs is: %f ", re);
printf("Do you want to continue? (y/n): ");
scanf(" %c", &answer);
} while (answer == 'y');
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.