G Dube
G Dube

Reputation: 147

How to calculate inputted values using a while loop c++?

How do you use a while loop only to add multiple values with a given point when to exit the loop and display the tallied amounts.

Note the following example. Test your program by entering 7 for the number of items and the following values for the calories: 7 - 120 60 150 600 1200 300 200

If your logic is correct, the following will be displayed: Total calories eaten today = 2630

Below is what I have written, what I require is understanding the calculation for the total calories.

#include <iostream>

using namespace std;

int main()
{
    int numberOfItems;
    int count = 1; //loop counter for the loop
    int caloriesForItem;
    int totalCalories;
    cout << "How many items did you eat today? ";
    cin >> numberOfItems;
    cout << "Enter the number of calories in each of the "
         << numberOfItems << " items eaten:  " << endl;

    while (count <= numberOfItems) // count cannot be more than the number of items
    {
        cout << "Enter calorie: ";
        cin >> caloriesForItem;
        totalCalories = ; //?
        ++count;
    }
    cout << "Total calories  eaten today  = " << totalCalories;

    return 0;
}

How do I store a value, then add on that value, repeatedly until the program reaches a point to exit as per the count value

Upvotes: 1

Views: 370

Answers (3)

Kitswas
Kitswas

Reputation: 1197

Logic Explained

Sourcecode

#include <iostream>

using namespace std;

int main()
{
    int numberOfItems;
    int count = 1; //loop counter for the loop
    int caloriesForItem;
    long totalCalories = 0;
    cout << "How many items did you eat today? ";
    cin >> numberOfItems;
    cout << "Enter the number of calories in each of the "
         << numberOfItems << " items eaten: " << endl;

    while (count <= numberOfItems) // count cannot be more than the number of items
    {
        cout << "Enter calorie: ";
        cin >> caloriesForItem;
        totalCalories = totalCalories + caloriesForItem;
        ++count;
    }
    cout << "Total calories eaten today  = " << totalCalories;

    return 0;
}

Upvotes: 2

kdelimaris27
kdelimaris27

Reputation: 1

You should increase the number of total calories in every loop. You can easily do that using the addition assignment operator (+=). It should look like this :

totalCalories += caloriesForItem;

Upvotes: 0

Tinchetsu
Tinchetsu

Reputation: 126

Also you can add them with += operator. But the result will be the same.

totalCalories += caloriesForItem;

Upvotes: 0

Related Questions