How to use a counter with a 'do while' loop in C++? - 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;
}

Related

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
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;

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.

C++ simple game using a Loop program

This program will play a game with the user, called Odds and Evens. The computer will play Evens, and the human user will play Odds. For a round of the game, each player picks an integer in the range [1,10]. The players pick their numbers independently: neither player knows the other player's number before choosing its own number. If the sum of the numbers is even, then Evens (the computer) wins that round; if the sum of the numbers is odd, then Odds (the human) wins that round. The game continues for as many rounds as the user want to play; the user ends the game by typing a non-# or a number outside [1,10] for the input. At the end of the game, the program summarizes the score.
I am having trouble properly looping this question. Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number. Also i do not know how I would have the program summarize the score. Help would be much appreciated as I have another problem for homework that is similar to this!
Here is my code:
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <string>
#include <iomanip>
#include <ctime>
using namespace std;
bool die(const string & msg);
int main(){
srand(static_cast<unsigned>(time(0)));
unsigned num1 = 0, num = 0, sum = 0;
bool userTurn = true;
cout << "Welcome to the Odds and Evens game!";
num = rand() % 10 + 1;
while (num){
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!";
}
else {
cout << " You win!";
}
}
userTurn = !userTurn;
}
}
bool die(const string & msg){
cout << "Fatal error: " << msg << endl;
exit(EXIT_FAILURE);
}
Randomizing the number pc chooses is not working as every round in the game the pc chooses the same number.
You don't have code to re-set the value of num when it's the computer's turn.
After the line
userTurn = !userTurn;
add
if ( !userTurn )
{
num = rand() % 10 + 1;
}
Also i do not know how I would have the program summarize the score.
Keep two counters that indicate how many times the human won and how many times the computer won.
int computerWinCount = 0;
int humanWinCount = 0;
and then, update the loop to use:
if (sum % 2 == 0){
cout << " I win!";
++computerWinCount;
}
else {
cout << " You win!";
++humanWinCount;
}
The conditional of the while loop is such that your program will never terminate. Update it to something like below.
while (true) {
if (userTurn){
cout << " Your # in [1,10] is ";
cin >> num1;
// If the user entered a number that is not
// within range or the user did not input a number,
// then break out of the loop.
if ( !cin || num1 < 1 || num1 > 10 )
{
break;
}
}
else {
cout << "My number is " << num;
sum = num1 + num;
if (sum % 2 == 0){
cout << " I win!" << endl;
++computerWinCount;
}
else {
cout << " You win!" << endl;
++humanWinCount;
}
}
userTurn = !userTurn;
if ( !userTurn )
{
num = rand() % 10 + 1;
}
}
To report the summary, add the following lines before the end of the main.
cout << "Number of times I won: " << computerWinCount << endl;
cout << "Number of times you won: " << humanWinCount << endl;
Here:
num = rand() % 10 + 1;
while (num){
... // never change num
}
Do you see the problem? The computer player chooses num randomly, but only once. Just put another num = rand() % 10 + 1; inside the main loop.
(Also, you don't seem to have a way for the user to terminate the game.)
So you want a simple loop that will do the following things.
get the user input.
get the computer input
check to see who win's the current round
update scores.
this happens until the user chooses an option not from 1 to 10
after this you want to display the score.
Here is a complete example.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
int mynum, compNum, myScore(0), compScore(0);
srand(time(NULL));
cout << "Welcome to the Odds and Evens game!" << endl;
cout << "Your # in [1,10] is ";
while ((cin >> mynum) && mynum > 0 && mynum <= 10){
compNum = rand()%10 + 1;
if ((mynum + compNum)%2){
cout << "You win" << endl;
++myScore;
} else {
cout << "Computer Wins" << endl;
++compScore;
}
cout << "Your # in [1,10] is ";
}
cout << "You won " << myScore << " games" << endl;
cout << "The computer won " << compScore << " games" << endl;
return 0;
}
Your problem with the computer's number not changing is due to the fact you do not update its value within the loop.
If you want to keep track of the score, you can simply keep two integers that keep track of how many times the user has won and how many times the computer has won. Then at the end (after the while loop) cout each of their scores.
Overall your code is pretty close.
You just need to make sure you update the computer's guess inside the while loop and when you decide who's won the round increment that person's score.
The whole loop condition in your original code will always evaluate to true. As num will always be to a number 1 to 10. You'll want to use the user's input in the while loop condition.
The while condition in my code will do the following:
get the user's input. cin >> mynum will evaluate to false if cin fails to read a number. If it did read a number the condition will check to see if the number is between 1 and 10 inclusive.

My simple C++ program calculates total payroll amount and I want to know a better and more efficient way to do this

I tried to implement the do..while loop in a simple program. In the program, I ask for a payroll amount, then calculate the sum of the payroll and outputs the sum and the number of valid entries. That's too simple so I decided to add some error checking.
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
const int SENTINEL = -1;
int main(){
int payroll, payroll_sum, counter = 0;
do{
cout << "Enter a payroll amount (-1 to end): ";
cin >> payroll;
if((payroll < SENTINEL)){
cout << "\nError!\nPlease enter a correct value.\n" << endl;
int main(payroll);
}
else{
payroll_sum += payroll;
counter += 1;
cout << "\n";
}
if(payroll == SENTINEL){
payroll_sum += 1;
counter -= 1;
}
}while(payroll != SENTINEL);
cout << "\n\nTotal payroll amount is: " << payroll_sum;
cout << "\nTotal number of entries is: " << counter;
return 0;
}
The code works, but it bugs me that I have to deduct one from the counter and add one to the sum because I don't know how to make the program ignore the SENTINEL input. And, I'm sure that there's a better way to do the error handling. Thanks in advance.
This is how I would have written it as it's quite a bit cleaner. A few things I noticed that you may want to take note of:
It's good practice to initiate variables when you declare them.
Read up about continue and break in loops as well as when to use a do-while or a while loop.
Happy coding!
const int SENTINEL = -1;
int main() {
int payroll_sum = 0;
int payroll = 0;
int counter = 0;
while (payroll != SENTINEL) {
cout << "Enter a payroll amount (-1 to end): ";
cin >> payroll;
if(payroll == SENTINEL) break;
if((payroll < SENTINEL)){
cout << "\nError!\nPlease enter a correct value.\n" << endl;
continue;
}
else {
payroll_sum += payroll;
counter++;
}
}
cout << "\n\nTotal payroll amount is: " << payroll_sum;
cout << "\nTotal number of entries is: " << counter;
return 0;
}
Use
continue;
Instead of
int main(payroll);
And also, initialize payroll_sum by using
payroll_sum=0
Before the loop. Also, remove
if(payroll == SENTINEL){
payroll_sum += 1;
counter -= 1;
}
And change the last two couts to
cout << "\n\nTotal payroll amount is: " << payroll_sum+1;
cout << "\nTotal number of entries is: " << counter-1;
Seems like a simple question about condition logic. There are plenty of different ways to structure your if conditions but one way that would be more efficient than your current code could be:
while(true)
{
cout << "Enter a payroll amount (-1 to end): ";
cin >> payroll;
if(payroll == SENTINEL)
break;
if((payroll < SENTINEL))
{
cout << "\nError!\nPlease enter a correct value.\n" << endl;
int main(payroll);
}
else
{
payroll_sum += payroll;
counter += 1;
cout << "\n";
}
}
If you don't like using while(true) I can provide another example. Cheers

How could I exit from do-while loop?

I have these block of codes that belong to a NIM subtraction game. The thing that I would like to implement is that user is going to be able play the game as long as he/she wants. Simply if user enters 999 program will exit, otherwise user will be playing until he/she enters 999. Here is my block of codes. I am not sure that I make a logical mistake or I need to add some specific exit code. Thanks for your time and attention.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int total, n;
while(true){
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if(total==999)
break;
while(true){
//pick best response and print results.
if ((total % 3) == 2)
{
total = total - 2;
cout << "I am subtracting 2." << endl;
}
else
{
total--;
cout << "I am subtracting 1." << endl;
}
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "I win!" << endl;
break;
}
// Get user’s response; must be 1 or 2.
cout << "Enter num to subtract (1 or 2): ";
cin >> n;
while (n < 1 || n > 2)
{
cout << "Input must be 1 or 2." << endl;
cout << "Re-enter: ";
cin >> n;
}
total = total - n;
cout << "New total is " << total << endl;
if (total == 0)
{
cout << "You win!" << endl;
break;
}
}
}
return 0;
}
You are modifying total inside the loop. Just test after cin>>total at the beginning if total==999 and break if true, i.e.
if(total==999)
break;
and replace the do-while loop by a while(true){}
In the do-while loop you are trying to compare character literal '999' with variable total that has type int.
}while(total!='999');
Though this code is valid its result can be something else than you are expecting. Values of character literals with more than one symbol are implementation defined.
You have to write
} while ( total != 999 );
Also if the player will enter 999 you start to play with him though you have to exit the game.
So in my opinion it is better to use while loop. For example
while ( true )
{
cout << "Welcome to NIM. \nEnter 999 to quit the game!\nPick a starting total: ";
cin >> total;
if ( total == 999 ) break;
// ...
}
you have to do three corrections in your code to make it right
first you have to check if total is equal to 999, then break in your do loop just after getting the total from user
second - you have to put same condition in your first while loop
and lastly - instead of while(total!='999') u shall write while(total!=999) because it is integer