I made a program that will loop and calculate the average of the input given by the user. There are no problems here. I just want to know if there is a better way to do this, or a way to optimize this code.
How this program works:
First, the program will read a double and a separator in a forever loop until it finds a newline character or a wrong separator. If it finds a space as separator, then it will just continue to read more input. If it finds newline, then it will print the average. If it finds anything else separator, e.g. 'a'
or '^'
, then it will print "error!".
The code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
double average, num, total;
char separator;
for(int i = 1; ; i++) //increment the value as the loop goes
{
scanf("%lf%c", &num, &separator);
total += num;
if(separator == '\n')
{
average = total / i;
printf("average = %lf\n", average);
break;
}
else if(separator == ' ')
{
//do nothing
}
else
{
while((getchar()) != '\n'); //clear buffer
printf("error!\n");
break;
}
}
printf("press ENTER to exit...");
getchar();
return 0;
}