In: Computer Science
Construct this program in C programming Please.
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 in a 0 or negative number the program should exit with a message to the user indicating they chose to exit. If the user has entered in 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 in the signal to stop as described previously.
Note: Function name and variable names used are arbitrary. These can be changed according to the user's choice. Please refer to code snippets for a better understanding of comments and indentations.
IDE Used: Dev C
Program Code
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// function that will that number of input and find average
float find_avg(int tot_inp)
{
// variables
int itr;
float inp_val;
// each input value
float tot_sum = 0; //
total sum
// start loop find average
for(itr = 0; itr < tot_inp; itr++ )
{
// get each number
printf("\nNumber %d :
",itr+1);
scanf("%f", &inp_val);
// calculate total sum
tot_sum += inp_val;
}
// return the average
return tot_sum/tot_inp;
}
int main()
{
// variables
int tot_inp; // total
input
bool more;
// more inputs true or false
float the_avg; // the
average storage variable
// do till user doesn't want to quit
do
{
// prompt user to enter total
number of inputs
// ask to stop by entering 0 or
negative value
printf("Input number of values to
enter (press 0 or negative value to terminate) : ");
scanf("%d",&tot_inp);
// if total input greater than
0
if(tot_inp > 0)
{
printf("\nEnter
%d values",tot_inp);
// call the
average finding function
the_avg =
find_avg(tot_inp);
// print the
average
printf("\nAverage of %d entered values is %0.2f\n",tot_inp,
the_avg);
// set more to
true i.e loop continue again
more =
true;
}
// else if 0 or negative
else
{
// printf exit
statement and set more to false i.e doesn't want to continue
printf("\nYou
choose to exit!! Quiting............");
more =
false;
}
}while(more == true);
return 0;
}
Code Snippets
Sample Output