c++ loop initializer and counters - c++

#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.

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;

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

How do i convert a while loop to a for loop in C++?

while (counter < total)
{
inFile >> grade;
sum += grade;
counter++;
}
Above is the while loop I had for my original program and below is my attempt at converting that to a for loop.
for (counter = 0; counter < total; counter++)
{
inFile >> grade;
cout << "The value read is " << grade << endl;
total = total + grade;
}
This is a simple program to get grade averages. Here is the entire program:
#include <iostream>
#include <fstream>
using namespace std;
int average (int a, int b);
int main()
{
// Declare variable inFile
ifstream inFile;
// Declare variables
int grade, counter, total;
// Declare and initialize sum
int sum = 0;
// Open file
inFile.open("input9.txt");
// Check if the file was opened
if (!inFile)
{
cout << "Input file not found" << endl;
return 1;
}
// Prompt the user to enter the number of grades to process.
cout << "Please enter the number of grades to process: " << endl << endl;
cin >> total;
// Check if the value entered is outside the range (1…100).
if (total < 1 || total > 100)
{
cout << "This number is out of range!" << endl;
return 1;
}
// Set counter to 0.
counter = 0;
// While (counter is less than total)
// Get the value from the file and store it in grade.
// Accumulate its value in sum.
// Increment the counter.
while (counter < total)
{
inFile >> grade;
sum += grade;
counter++;
}
// Print message followed by the value returned by the function average (sum,total).
cout << "The average is: " << average(sum,total) << endl << endl;
inFile.close();
return 0;
}
int average(int a, int b)
{
return static_cast <int> (a) /(static_cast <int> (b));
}
I tried to convert while loop to a for loop but when I debug I get an infinite loop. There are no errors when I build my solution. I'm not sure what other details to add.
You are increasing the value of total in the for loop. Hence, counter never reached total if you keep entering positive values.
Perhaps you meant to use sum instead of total in the loop.
for (counter = 0; counter < total; counter++)
{
inFile >> grade;
cout << "The value read is " << grade << endl;
sum = sum + grade;
}
You are using wrong variables names, value of total is increasing in the for loop so it becomes an infinite loop, use a different variable names for storing sum and for for-loop termination condition.

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.

Drop lowest input from Array?

I have to find the lowest input given, then average out the total minus the lowest score. I am having a bit of trouble with my averageScore function finding the lowest score from the array. I am getting very odd numbers as my output. Any suggestions on how to adjust this would be appreciated. Thanks in advance.
#include <iostream>
#include <cstdlib>
using namespace std;
//function prototypes
double* allocate(int&);
double averageScore(int&);
int main()
{
double* testArray;
int numOfScores;
double average;
testArray = allocate(numOfScores);
average = averageScore(numOfScores);
//delete memory created
delete[] testArray;
return 0;
}
//function to collect user info, dynamically allocate
double* allocate(int &numOfScores)
{
double* testArray;
//prompt user for scores
cout << "How many test scores would\n";
cout << "you like to process: ";
//user input validation
if(!(cin >> numOfScores))
{
cout << "Invalid input!\n";
cout << "Program termination, please\n";
cout << "restart the program." << endl;
exit(0);
}
else if(numOfScores < 0)
{
cout << "Invalid input!\n";
cout << "Program termination, please\n";
cout << "restart the program." << endl;
exit(0);
}
//dynammically allocate an arrray to hold the scores
testArray = new double[numOfScores];
//get the scores from user
for (int count = 0; count < numOfScores; count++)
{
cout << "Enter Score: ";
//user input validation
if(!(cin >> testArray[count]))
{
cout << "Invalid input!\n";
cout << "Program termination, please\n";
cout << "restart the program." << endl;
exit(0);
}
else if(testArray[count] < 0.0)
{
cout << "Invalid input!\n";
cout << "Program termination, please\n";
cout << "restart the program." << endl;
exit(0);
}
}
return testArray;
}
//function to calculate the average score
double averageScore(int &numOfScores)
{
double* testArray;
double total,
average,
scores[0],
lowest;
lowest = scores[0];
//calculate total scores entered
for(int count = 0; count < numOfScores; count++)
{
total += testArray[count];
//find lowest score entered
for(int count = 1; count < numOfScores; count++)
{
if (testArray[numOfScores] < lowest)
lowest = scores[numOfScores];
}
}
//average the total amount of scores drop the lowest
average = (total - lowest) / numOfScores;
cout << "The average test score is: " << average << endl;
cout << "Lowest is: " << lowest << endl;
return average;
}
std::vector<double> scores = {1.2,6.5,3.0,8.3,4.8,6,7.7};
// drop lowest score
scores.erase(min_element(begin(scores),end(scores)));
double average = accumulate(begin(scores),end(scores),0.0)/scores.size();
Couple issues. You shouldnt have those two for loops nested(instead just check if the value is lower than the lowest using an if statement).
Since this is homework I will give you the steps and then you can fix your code
Loop through and calculate the total, finding the lowest score at the same time
Calculate the average as (total-lowest)/(numScores -1)
Return the average
I think you want to change this line:
if(testArray[numOfScores] < lowest)
to this:
if(testArray[count] < lowest)
Also, as #jzworkman points out, the denominator for averaging should be (numScores - 1) since you are eliminating the lowest score from the numerator. (If applicable, you might want to test for the edge case where there is only one score, which leaves nothing to average once you eliminate the lowest score.)
There are a lot of problems with your averageScore function, but i'll cover the most basic one for now.
First off, you should pass it some sort of data. Right now you're using testArray I don't even see where it is allocated. I'm surprised that you're not getting segmentation faults when you run this.
But it's also not initialized. In c++, when you declare a pointer, the variable it points to has a value. It has a garbage value, and if you perform arithmetic operations with that garbage value, then your output will be garbage too.
You have to make your list of scores available to your averageScore function, preferably by passing them in as a parameter.
the beginning of your averaging function looks like the following:
double averageScore(int &numOfScores)
{
double* testArray;
...
instead it should look like this
double averageScore(double*testArray, int numOfScores)
{
...
when you use &numOfScores instead of numOfScores, that means that if you change numOfScores in your averageScore function, than it will change in your main function as well, and you shouldn't do that.
now, on the double* testArray; line, you're declaring a brand new pointer, named "testArray", and there's no meaningful data in it, although it might be full of garbage. there might be other double pointer variables, named "testArray" in your code, but none of them are in the scope of your averageScore function. If you pass testArray in, in your method call, you'll then be able to use it. for example: double someNumber = testArray[i].
Bare in mind that your array is also being passed by reference. If you would rather pass it by value, you can try
`double averageScore(double testArray[], int numOfScores)`
but don't quote me on that one
Once you've done that, your code will still have some issues, but the output should be meaningful enough that you'll hopefully be able to work those out on your own.