averagec include Read a set of values from the user Store
average.c
~~~~~~~~~~~~~~~~~
#include <stdio.h>
/*
Read a set of values from the user.
Store the sum in the sum variable and return the number of values read.
*/
int read_values(double sum) {
int values=0,input=0;
sum = 0;
printf(\"Enter input values (enter 0 to finish):\ \");
scanf(\"%d\",&input);
while(input != 0) {
values++;
sum += input;
scanf(\"%d\",input);
}
return values;
}
int main() {
double sum=0;
int values;
values = read_values(sum);
printf(\"Average: %g\ \",sum/values);
return 0;
}
Solution
Hi,
I have fixed the issues and highlighted the code changes below
#include <stdio.h>
/*
Read a set of values from the user.
Store the sum in the sum variable and return the number of values read.
*/
int read_values(double &sum) {
int values=0,input=0;
sum = 0;
printf(\"Enter input values (enter 0 to finish):\ \");
scanf(\"%d\",&input);
while(input != 0) {
values++;
sum += input;
scanf(\"%d\",&input); //segment fault error
}
return values;
}
int main() {
double sum=0;
int values;
values = read_values(sum);
printf(\"Average: %g\ \",sum/values);
return 0;
}
OUtput:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Enter input values (enter 0 to finish):
4
5
6
7
3
0
Average: 5

