How Many Calories?
This programming challenge is from an initial C++ programming course I took in Fall 2007. The Chapter (3) was titled “Expressions and Interactivity”.
I post these old academic challenges for a few reasons. One is to demonstrate my programming learning, experience, and progression. Another reason is to make sure my code and solutions are indexed by search engines, so that other beginning programmers may get help if they need it.
3.7: A bag of cookies holds 40 cookies. The calorie information on the bag claims that there are 10 “servings” in the bag and that a serving equals 300 calories. Write a program that asks the user to input how many cookies they actually ate and then reports how many total calories were consumed.
My solution:
/* Chapter 3 Challenge 7
Written by Kirk Hingsberger
September 18, 2007
How many calories?
*/
#include
using namespace std;
int main()
{
const float COOKIES_PER_BAG = 40;
const float SERVINGS_PER_BAG = 10;
const float CALORIES_PER_SERVING = 300;
float cookiesPerServing = COOKIES_PER_BAG / SERVINGS_PER_BAG;
float caloriesPerCookie = CALORIES_PER_SERVING / cookiesPerServing;
float cookiesEaten, caloriesConsumed;
cout << "There are " << cookiesPerServing << " cookies per serving." << endl;
cout << "There are " << caloriesPerCookie << " calories per cookie." << endl;
cout << "How many cookies did you eat?" << endl;
cin >> cookiesEaten;
caloriesConsumed = cookiesEaten * caloriesPerCookie;
cout << "If you ate " << cookiesEaten << " cookies, then you consumed ";
cout << caloriesConsumed << " total calories." << endl;
return 0;
}
Here is the capture script I turned in for grading:
Script started on Thu 20 Sep 2007 09:52:43 AM MDT
$ cat chap3chlg7.cc
/* Chapter 3 Challenge 7
Written by Kirk Hingsberger
September 18, 2007
How many calories?
*/
#include
using namespace std;
int main()
{
const float COOKIES_PER_BAG = 40;
const float SERVINGS_PER_BAG = 10;
const float CALORIES_PER_SERVING = 300;
float cookiesPerServing = COOKIES_PER_BAG / SERVINGS_PER_BAG;
float caloriesPerCookie = CALORIES_PER_SERVING / cookiesPerServing;
float cookiesEaten, caloriesConsumed;
cout << "There are " << cookiesPerServing << " cookies per serving." << endl;
cout << "There are " << caloriesPerCookie << " calories per cookie." << endl;
cout << "How many cookies did you eat?" << endl;
cin >> cookiesEaten;
caloriesConsumed = cookiesEaten * caloriesPerCookie;
cout << “If you ate ” << cookiesEaten << ” cookies, then you consumed “;
cout << caloriesConsumed << ” total calories.” << endl;
return 0;
}
$ g++ -o chap3chlg7 chap3chlg7.cc -s
$ chap3chlg7
There are 4 cookies per serving.
There are 75 calories per cookie.
How many cookies did you eat?
10
If you ate 10 cookies, then you consumed 750 total calories.
$ exit
exit
Script done on Thu 20 Sep 2007 09:53:17 AM MDT










