How to calculate inputted values using a while loop c++? - 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

Logic Explained
Initialize totalCalories to 0 outside the loop. This is required to prevent undefined behaviour. You may refer to (Why) is using an uninitialized variable undefined behavior? and Default variable value.
For every item, add caloriesForItem to totalCalories. You may also use the += operator if you are familiar with it.
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;
}

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

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;

Related

How to use a counter with a 'do while' loop in C++?

I am trying to get this 'do while' loop to run 3 times and then display the amount in the accumulator contain within a while loop inside the 'do while' loop.
It seems to be counting correctly, but only runs the while loop on the first. When run, instead of going on to ask for the next set of numbers, it just displays the first batch (added up correctly). I have tried switching some of the code around and searching google, but can't find the answer.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int storeNum = 1;
int payRollAmount = 0;
int totalPayroll = 0;
do
{
cout << "Store " << storeNum << ":" << endl;
while (payRollAmount <= -1)
{
cout << "Enter Store's Payroll Amount (-1 to exit): ";
cin >> payRollAmount;
totalPayroll += payRollAmount;
}
storeNum++;
} while (storeNum <= 3);
cout << "The Total Payroll is: " << totalPayroll << endl;
system("pause");
return 0;
}
The code should take in an unknown amount of "payrolls," allow you to exit using -1, and then continue on to the next stores payrolls. It should do this 3 times, and then display the total amount (all numbers entered added together.
Hi perhaps reset payRollAmount at each iteration? That way it will continue to request the input.
for (int amount = 0; amount != -1; ) {
cout << "Enter Store's Payroll Amount (-1 to exit): ";
cin >> amount;
totalPayroll += amount;
}

c++ loop initializer and counters

#include <iostream>
using namespace std;
int main()
{
int score;
int numTests;
int total = 0; //why total has to be set to 0
double average;
cout << "How many tests: ";
cin >> numTests;
int s = 1;
while (s <= numTests)
{
cout << "Enter score # " << s << ": "; // why put the s there ???
cin >> score;
total += score;
s++; //why update the counter
}
cout << "total" << total << endl;
average = (double)total / numTests;
cout << "Average" << average << endl;
system("pause");
return 0;
}
1.My question is that why does the integer total has to be put as value 0? (int total = 0)
2.on the line that I enter the score number why do I have to input the counter s on it? (cout << "Enter score # " << s <<)
3.and why do I have the update the counter (s++)?
Question 1. in c++ and c when you defined a variable the default of value is anything from memory and its not null or 0
Question 2. cout<< is for print data and when you write cout<
Question 3. s++ mean s=s+1; and this is for the loop end while (s <= numTests)
Before you start counting the scores from the tests, naturally the total number is 0.
You put the counter s to indicate which score should be entered, i.e. "score 1", "score 2", etc... It is there for clarification of the user. Imagine you are on the other side and want to see your average from 20 tests, but each time it just shows: "Enter score:" - first, you will not be sure it works, second, at some point you might become distracted and forget how many scores you have entered. So this shows you exactly where you are at.
s++ means each time the counter increases with 1. So, when it reaches the number of tests, the loop will not continue. The counter is used as a condition for the while loop - so that the cycle will stop and not go inifinitely.

What container to use when I need to know both the max value and who has achieved it?

I'm trying to work through the beginner exercises from a website.
"Requires:
variables, data types, and numerical operators
basic input/output
logic (if statements, switch statements)
loops (for, while, do-while)
arrays
Write a program that asks the user to enter the number of pancakes eaten for breakfast by 10 different people (Person 1, Person 2, ..., Person 10)
Once the data has been entered the program must analyze the data and output which person ate the most pancakes for breakfast."
I'm unsure on how to get the program to call out the person which enters the most number of pancakes eaten? Surely this would need to be done with a key and value, but the requirements state 'arrays' but not 'maps'?
Below is the code I have come up with, but this only outputs the maximum number of pancakes eaten, so not really answering the question!
Thanks so much for any help!
* I've only used 5 people to quicken the process before I know exactly how to do it *
#include <iostream>
using namespace std;
int main()
{
cout << "how many pancakes did you eat for breakfast?" << endl;
int person1, person2, person3, person4, person5;
cout << "Person 1: ";
cin >> person1;
cout << "Person 2: ";
cin >> person2;
cout << "Person 3: ";
cin >> person3;
cout << "Person 4: ";
cin >> person4;
cout << "Person 5: ";
cin >> person5;
int array[5] = {person1, person2, person3, person4, person5};
int temp = 0;
for (int i = 0; i<5; i++)
{
if (array[i] > temp)
{
temp = array[i];
}
}
cout << "The most pancakes eaten was " << temp << "by " << endl;
}
Surely this would need to be done with a key and value
This is not the only way of doing it. Another way is to use an indexed collection with no key, and make an assumption that position k corresponds to a key k that can be computed from a position alone. For example, if you have an array of ten items corresponding to ten people numbered 1 through 10, then the data for a person number k could be stored in the array at position k-1. No keys are required in this situation.
This long explanation means that if you store the best i in addition to best tmp, you'll have your answer after the loop:
int temp = 0;
int res = -1;
for (int i = 0; i<5; i++) {
if (array[i] > temp) {
temp = array[i];
res = i;
}
}
cout << "The most pancakes eaten was " << temp << "by " << (res+1) << endl;
Note the res+1 is printed, not res. This is because arrays are zero-based, while counting is one-based.
This could be further shortened using a common idiom of using the initial element as the current best, and starting your iterations from 1:
int res = 0;
for (int i = 1 ; i<5 ; i++) {
if (array[i] > array[res]) {
res = i;
}
}
cout << "The most pancakes eaten was " << array[res] << "by " << (res+1) << endl;
What if you kept track of the maximum amount of pancakes eaten as you took input?
#include <iostream>
using namespace std;
// To execute C++, please define "int main()"
int main() {
int numPeople = 5;
int maxPancakes = -1;
int maxPerson = -1;
int currentPancakes = -1;
for (int i = 1; i < numPeople; i++) {
cout << "Person " << i << ": ";
cin >> currentPancakes;
if (currentPancakes > max) {
max = currentPancakes;
maxPerson = i;
}
}
cout << "Person " << maxPerson << " ate the most pancakes: " << maxPancakes;
return 0;
}
Note: my c++ is pretty rusty, I haven't tested this solution. Just an idea ;)
Using Map for this question will be an overkill. Array is more than enough. You don't even need to iterate through the array to check who ate the most. The operation for getting the max is actually O(0) because we can update who ate the most as you are entering the values.
int main(){
const int NUM_PEOPLE = 10;
int cakesEaten[10] = {0};
int maxEaten = 0;
int personId = 0;
cout << "How many pancakes eaten by:" << endl;
for(int x=0; x<NUM_PEOPLE; x++){
cout << "person " << (x+1) << ":";
cin >> cakesEaten[x];
if (cakesEaten[x] > maxEaten){
maxEaten = cakesEaten[x];
personId = x;
}
}
cout << "The most pancakes was eaten by person " << personID << endl;
}
You don't need any storage at all.
As the numbers are entered, compare them and store who has the current max, and its value
Starting with fake values is not needed if you use the first person's value as the start value, this way negative values, could be included if entered. That may be nonsensical here, but in general, its a better practice.
Also note if we want people to start at 1, then it makes more sense to start it at 1, then start at 0 and try to remember to always add 1.
This is also very easy to expand to more people, just change total_people
int main() {
const int total_people=5;
cout << "how many pancakes did you eat for breakfast?" << endl;
int what;
cout << "Person 1: ";
cin >> what;
int who=1;
int max_value=what;
for (int person = 2; person <= total_people; ++person) {
cout << "Person " << person << ": ";
cin >> what;
if (what > max_value) {
max_value=what;
who=i;
}
}
cout << "The most pancakes eaten was " << max_value << "by " << who << endl;
}

C++ Array parameters and const value

I do not get arrays, Im sure there are easier ways to make this program but I must do it the teacher's way and I am lost.
This is the assigment:
I do not get how I should go about these arrays. most confusing thing I seen by far.
What I would like is a guide or help on how i should program these arrays or how I should program arrays period. Not asking to do the rest for me, I already know how to do most of this, its just the arrays I like to know how to do.
This is my current program:
#include<iostream>
using namespace std;
void getPoints(int pPossible[], double pEarned[], int numItems, int limit);
int sumArray(double
void getpoints(int pPossible[], double pEarned[], int numItems, int limit)
{
int count;
while (limit == limit)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numbItems > limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
count=1;
for(count=1; count<numItems; count++)
cout << "Enter points then points possible for Item " << count << ": ";
cin << pEarned[count] << pPossible[count];
return 0;
}
C++ array indexes are zero-based, so you should use zero for the initial value in the for loop. Also, you're missing the braces for the for loop body; as it is, it will run the cout line numItem-1 times and the cin line just once.
Another thing: the operators in the for's cin line should be >>, not <<. You want input here, not output.
Finally, like #ebyrob said, make numItems a reference parameter (it would be clearer for the caller to use a pointer instead, but the assignment asked for a reference parameter).
void getpoints(int pPossible[], double pEarned[], int& numItems, int limit)
{
//Read number of items
while (true)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numItems >= limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
//Read earned and possible for each item
for(int count=0; count<numItems; count++)
{
cout << "Enter points then points possible for Item " << count << ": ";
cin >> pEarned[count] >> pPossible[count];
}
return 0;
}

Getting a sum from multiple inputs using a for loop?

I have to write a program that uses a for loop to ask how many floors are in a hotel, then ask the user for the number of rooms on each floor and the number of rooms occupied. At the end I'm to add up all the rooms, how many are occupied and not occupied, and give percentages based on those numbers. So far all I have is the loop, and my sum feature now gives me outrageous numbers.
#include <iostream>
using namespace std;
int main ()
{
int floor, room, occupy, total_unoccupy, total_occupy, total_room;
cout << "How many floors are in the hotel?\n";
cin >> floor;
for ( ;floor >= 1; floor--)
{
cout << "How many rooms are on floor " << floor << "?" << endl;
cin >> room;
cout << "How many of these rooms are occupied?" <<endl;
cin >> occupy;
}
total_room += room;
cout << "The total number of rooms are " << total_room << "." << endl;
return 0;
}
Move total_room += room; inside the for loop.
for ( ;floor >= 1; floor--) {
cout << "How many rooms are on floor " << floor << "?" << endl;
cin >> room;
total_room += room;
cout << "How many of these rooms are occupied?" <<endl;
cin >> occupy;
total_occupy += room;
total_unoccupy += room-occupy;
}
Also, you need to change this line:
int floor, room, occupy, total_unoccupy, total_occupy, total_room;
To this:
int floor = 0, room = 0, occupy = 0, total_unoccupy = 0, total_occupy = 0, total_room = 0;
You should initialize the variables like total_occupy = 0 etc... otherwise you can have unexpected results.
Regards
nothing left to be answered thanks for nhgr
Moreover, in case multiplication, you need to initialize the total variable as 1.