Simple C Example – Average Finder

16 03 2008

int main()
{
double x = 0.0, sum = 0.0;
int count = 0;

printf( "\t--- Calculate Averages ---\n" );
printf("\nEnter some numbers:\n"
"(Type a letter to end you input)\n" );
while ( scanf("%lf", &x ) == 1)
{
sum += x;
count++;
}

if (count == 0)
{
printf("No Input Data!\n");
}
else
printf("The Average of your numbers is %.2f\n", sum/count);
return 0;
}

This is a basic loop that lets you put in as many numbers as you want to, and then a letter to get the average of all said numbers. Very simple, but shows good use of basic constructs in C


Actions

Information

Leave a comment