fork download
  1. /* Program will calculate the average cost of groceries */
  2. /* User will be prompted for number of weeks and grocery bill per week */
  3.  
  4. #include <stdio.h>
  5.  
  6. int main(void)
  7. {
  8.  
  9. /* Declare variables */
  10. int count, maxweek, weekNum;
  11. float grocerybill, sum, avg;
  12.  
  13. /*Initialize value */
  14. count = 0;
  15. maxweek = 0;
  16. sum = 0;
  17. avg = 0;
  18. weekNum = 0;
  19.  
  20. //Ask user for the number of weeks to calculate
  21. printf("How many weeks do you want to calculate? \n");
  22. scanf("%d", &maxweek);
  23.  
  24. //Display number of weeks
  25. printf("You've requested %d weeks\n", maxweek);
  26.  
  27. //Loop through maxweeks of groceries
  28. while (count<maxweek)
  29. {
  30. printf("Enter grocery bill for week# : \n", weekNum);
  31. scanf("%f", &grocerybill);
  32. //printf("\nfood", grocerybill);
  33.  
  34. if (grocerybill >=0) {
  35. sum = sum + grocerybill;
  36. count = count + 1;
  37. weekNum = weekNum + 1;
  38.  
  39. }
  40. else {
  41.  
  42. printf("Value should be greater or equal to zero\n");
  43. }
  44. }
  45.  
  46. //Calculate average groceries over maxweeks
  47. avg = sum / count;
  48.  
  49. //Display average groceries
  50. printf("Average spent in groceries is %.2f\n", avg);
  51.  
  52. return 0;
  53. }
Success #stdin #stdout 0s 9432KB
stdin
4 100 100 200 200
stdout
How many weeks do you want to calculate? 
You've requested 4 weeks
Enter grocery bill for week# : 
Enter grocery bill for week# : 
Enter grocery bill for week# : 
Enter grocery bill for week# : 
Average spent in groceries is 150.00