Friday, July 31, 2009

C Programming: How do you calculate the average in a loop?

hi guys, i just want to ask something about this program im making for my assignment.





im supposed to make a program that will display numbers 10 to 100 with intervals of 10, in the left column and the profit(5% of the sales) on the right column. after the loop ends, the average of the sales should be displayed at the bottom. and my question is... whats the code for calculating the average of the loop?





here's my code:





#include %26lt;stdio.h%26gt;





void main()


{


float sales, avg;





printf("Sales Projection (in thousands).\n\n");


printf("\tSales\tProfit\n");





for (sales=10;sales%26lt;=100;sales+=10)





{


printf("\t$%.f\t$%.2f\n",sales, sales*0.05);


}





printf("\n\tAverage Sales: $%.2f", avg);





}








any help would be very much appreciated ^^

C Programming: How do you calculate the average in a loop?
The average is the sum of the items divided by the number of items. But you knew that.





Declare a variable to hold the sum and initialize it outside the loop





float, sales, avg, sum;





sum = 0;





While you are printing out the sales, keep a running total inside the loop





sum += sales;





after the loop, calculate the average





avg = sum / 10;





In the more general case, you'd know beforehand or calculate how many items you added up, and you'd divide by that instead of by the constant 10.
Reply:Use below code


#include %26lt;stdio.h%26gt;





void main()


{


float sales, avg=0.0;





printf("Sales Projection (in thousands).\n\n");


printf("\tSales\tProfit\n");





for (sales=10;sales%26lt;=100;sales+=10...





{


printf("\t$%.f\t$%.2f\n",sales... sales*0.05);


avg+=sales;


}


avg/=10;


printf("\n\tAverage Sales: $%.2f", avg);





}


No comments:

Post a Comment