stuck in a infinite do while loop - c++

I am trying to make a simple guess my number game in c++ but the computer need to guess my number. But the problem is that I am stuck in this infinite loop. I am just a beginner so it's a really basic program.
This is my code:
int secretNumber = rand() %100 + 1; // random number between 1-100
int tries=0;
int input;
cout <<"typ your number\n";
cin >> input;
do
{
cout <<secretNumber <<endl;
++tries;
if (secretNumber > input)
{
cout <<"To high i guess?\n";
}
else if (secretNumber < input)
{
cout <<"To low I guess?\n";
}
else
{
cout <<"Yes, i got it in " <<tries <<" tries!";
}
}while (input != secretNumber);
return 0;
}

place cin >> input into loop body

I think you should move the random number generation inside the loop.

The value of the variable input is never changed in the loop, so the terminating condition input != secretNumber is never met.
You should take the input inside the loop. So write cin >> input at the beginning of the loop.
Edit:
If the computer should guess, then still the value of input needs to be changed in the loop, which is not present in your code. The loop runs with the same value in input every time.
To make you computer make a guess, you should follow some scheme. The computer may draw the numbers at random - which you can get through moving secretNumber = rand()%100 + 1 inside the loop. But this approach may not perform good, the loop may still run for a very long time. This is shown in #Kaii's answer.
A more efficient approach is the Binary Search. In this case you should keep track of the guesses the computer makes. Keep two variables high and low which should store the guesses higher and lower than input respectively. Whenever a guess in higher than the number, store it in high, and store any guess lower than input in low. Then the computer should try its new guess between high and low. A random guess should be secretNumber = low + rand() % (high - low). In worst case it will take as much as 100 iterations. For the best results, each guess should be (high + low) / 2. According to the conditions, one of high and low will be updated in each iteration. This approach will ensure that the computer will guess the correct number within 7 guesses.
In your code it should be like this:
int secretNumber = rand() % 100 + 1; // random number between 1-100
int tries=0;
int input;
int low = 1, high = 100;
cout <<"typ your number\n";
cin >> input;
do
{
secretNumber = (high + low) / 2;
cout << secretNumber <<endl;
++tries;
if (secretNumber > input)
{
cout << "Too high I guess?\n";
high = secretNumber;
}
else if (secretNumber < input)
{
cout << "Too low I guess?\n";
low = secretNumber;
}
else
{
cout << "Yes, i got it in " << tries << " tries!";
}
} while (input != secretNumber);
return 0;

the computer is only guessing (by random) once when the program starts, but should guess each time the loop is iterated. you should move the random number generation inside the loop:
int secretNumber = 0;
int tries=0;
int input;
cout <<"typ your number\n";
cin >> input;
do
{
/* the fix is here */
secretNumber = rand() %100 + 1; // random number between 1-100
cout <<secretNumber <<endl;
++tries;
if (secretNumber > input)
{
cout <<"To high i guess?\n";
}
else if (secretNumber < input)
{
cout <<"To low I guess?\n";
}
else
{
cout <<"Yes, i got it in " <<tries <<" tries!";
}
}while (input != secretNumber);
return 0;

You have to do the input within the loop. Right now you prompt for a value BEFORE you start looping, then never ask the user for another number. If the guess can't be changed, the loop can never exit.
changing to
do {
cin >> input;
will solve the infinite loop.

infinite loop in your code because the argument for while always true until you get the true number.
you need to add another argument. example you want set maximal tries to 5 times. then it will be like this
do{
//do your stuff here
}while((input != secretNumber)&&(tries<=5))
when you input wrong number for 5 times, the application will finish

Related

c++ srand(time(0)) doesn't work in guessing game

I need to make a guessing game in C++, and everything works except that srand(time(0)) doesn't reset the number after the user wants to play again. I also can't use std libraries.
Nothing I have done has worked so far. Am I doing the while loops wrong?
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
//Initialize variables
int input = 0;
int playing = 1;
char yninput[2];
int count = 1;
//While the player is playing the game
while (playing == 1) {
srand(time(0));
int num = rand() % 101;
//While the player hasn't guessed the number
while (input != num) {
//Prompt the player
cout << "Enter your guess" << endl;
cout << num << endl;
cin >> input;
//If the guess is greater than the number
if (input > num) {
cout << " Your guess is too high!" << endl;
count++;
}
//If the guess is less than the number
else if (input < num) {
cout << " Your guess is too low!" << endl;
count++;
}
//If the player guesses the correct number
else {
cout << " You have guessed the number! It took you " << count << "
guess(es)! Would you like to play again?" << endl;
//Ask the play if they want to play again
cin >> yninput[2];
//If the player doesn't want to play again quit the program
if (yninput[2] == 'n') {
playing = 0;
input = num;
}
//If the player wants to play again restart the program and
randomize the number
else if (yninput[2] == 'y') {
input = 0;
count = 1;
}
}
}
}
}
As #user4581301 has pointed out, you shouldn't call srand(time(0)) more than once, as it will reset the random seed according to the current system time. If srand(time(0)) is called in rapid succession, the very big number that it will take as a seed (which I believe is the current epoch time) will be sufficiently close to the previous call that you might not observe significant difference in your RNG.
Simply moving the srand(time(0)); line out of the while loop should do the trick.
How do I get it so that when the user presses 'y' and the game resets that the random number also changes?
You get the next number in the pseudo random sequence by calling rand without calling srand in between. If you set the random sequence to start from the current timestamp on every iteration, then you get the same number which changes once a second.
I also can't use std libraries.
srand, rand, time, cout and cin are all from the standard library.
I think #Mathis has already pointed out the solution.
I am just sharing some insight as to how srand and rand are related. Consider the below code snippet:
#include <iostream>
#include <ctime>
int main()
{
int i = 0;
// Uncomment below line to generate new set of random numbers
// on every execution.
// srand(time(0));
while (i < 5)
{
std::cout<< rand() % 10 <<std::endl;
}
}
Let's say the program generates numbers - 5, 7, 3, 0 and 4 on 1st run. If you run the program again, you will see the same set of numbers, i.e, 5, 7, 3, 0 and 4. So, although they are random (pseudo random to be precise), but on every program execution, the order of numbers will be same.
This is the reason we use srand to specify some seed value. Seed is any value which is different on each execution. When we use time(0) as parameter to srand, we make sure that on every program execution, we are providing a new and unique seed. This will make sure that we get truly random set of numbers.

What is the relevance of if (!(cin >> variableName)) in this loop

I'm a self taught developer trying to learn c++, I found this exercise on google and I wrote the code for it, though all my conditions were correct, it wouldn't work, when I checked their answer, I found this line of code- if (!(cin >> guess)). I honestly don't see the relevance, I don't know why it made my loop not to work. Here is my code:
int main(int argc, char* argv[])
{
int nUserRandNum = 0;
int randomNumber=0;
srand (time(NULL));
randomNumber = rand() % 100 + 1;
printf("Please enter a random number between 1 - 99 \n");
scanf("%d", &nUserRandNum);
do
{
if (randomNumber < nUserRandNum)
{
printf("Try to go a little higher than \n", nUserRandNum);
}
else
{
printf("You might want to go a little lower than \n", nUserRandNum);
}
}
while (randomNumber != nUserRandNum);
printf("You got it!!!");
system("Pause");
return 0;
}
When I checked the answer they had:
int random_number, guess;
// Initialize random seed.
srand (time(NULL));
// Generate random number between 1 and 100
random_number = rand() % 100 + 1;
cout << "Guess our number (1 to 100) ";
cin>>guess;
do
{
if (!(cin >> guess))
{
cout << "Please enter only numbers" << endl;
}
else
{
if (random_number < guess)
cout << "The secret number is lower than " << guess << endl;
else if (random_number > guess)
cout << "The secret number is higher than " << guess << endl;
}
} while (random_number != guess);
cout << "Congratulations!" << endl;
what does that if statement do {if (!(cin >> guess)) }? And are there other reasons my loop didn't work?
The difference between scanf and cin >> is not relevant here, that's not what makes it work.
Here's what you have:
scanf("%d", &nUserRandNum);
do
{
... print ...
}
while (randomNumber != nUserRandNum);
Your scanf is outside of the loop. Therefore, when the do...while condition is satisfied, the same number that the user already entered is checked again.
This needs to be inside the loop body, like so:
do
{
scanf("%d", &nUserRandNum);
... print ...
}
while (randomNumber != nUserRandNum);
Reading input from cin rather than using scanf is probably a good idea, as it's less easy to get wrong. (Although the code you've shown still manages to do so.)
Checking whether a number was successfully read is probably a good idea too. When the user enters random garbage, you shouldn't treat that as if the user had entered a number.
But neither of those is the cause of your problem.
You can understand that if (!(cin >> guess)) statement as "if inputting the number was unsuccessful", so (cin >> x) is true if the type entered by the user really is an int.
Nitpick: you switched "go lower" with "go higher" by the way.

Simple while loop not terminating (beginner)

Here's what I want my program to do. Prompt the user to input 10 integers. Then my program adds up the even integers, adds up the odd integers, then displays both sums. Simple beginner's exercise. To do this, I'm using a while loop with a control variable. Here is the entirety of my code:
#include <iostream>
using namespace std;
int main()
{
int evenSum = 0;
int oddSum = 0;
int num;
int control = 0;
cout << "Enter 10 integers: " << endl;
cin >> num;
while (control <= 10)
{
if (num%2 == 0)
{
evenSum = evenSum + num;
}
else
{
oddSum = oddSum + num;
}
control++;
cin >> num;
}
cout << "The sum of the even integers is " << evenSum << endl;
cout << "The sum of the odd integers is " << oddSum << endl;
return 0;
}
To test this code, I'm using as input the first 10 positive integers, 1-10. However, I'm having a couple headaches. First, control never passes from the while loop, i.e. the program never gets to the point where it displays the evenSum and outSum variable values. I'm having a hell of a time figuring out why the while loop never terminates. As I've written it, the while condition will become false as soon as control = 11, and the control variable is incremented at the end of the while body, so it should not keep going. Yet it does.
My second headache (probably related) is that the sum of the even numbers in my input should be 30, and the sum of the odd numbers should be 25. However, while my program gets the oddSum correct, it only sums the evens up to 20, so it is not counting the last number (10) for some reason.
I have walked through this program carefully several times on paper. Also, I've had it display the variable values as it goes, so I can track what it is doing with each while loop. Eventually, it just stops displaying output, but without ever actually terminating. And it sums the evens and odds correctly, just without adding that last number.
It seems to me there is at least one off-by-one error here, possible 2 that are compounding each other. But I have tried adjusting my various values and it's nothing doing. My other thought is that I'm suspicious of the way I have set up my input stream. I.e. I'm unsure of what value will be assigned to num in the final iteration of the while loop.
Can anyone shed some light on either of these problems?
Read at the top of your loop (after checking the count)
// cin >> num;
while (control <= 10)
{
cin >> num;
if (num%2 == 0)
{
evenSum = evenSum + num;
}
else
{
oddSum = oddSum + num;
}
control++;
// cin >> num;
}
Try to trace the code execution. Manually. That is the best way to learn how computers think.
You’ll realize, that the loop condition is broken. You start counting from 0, continue up to 10 including, stop at 11. 0..10, that’s 11 numbers!
Furthermore, you are reading input once at the beginning and then once at the end of each iteration. That makes 12 reads.
When trying to read more input than supplied, the program blocks and waits for more input. A program in infinite loop is active, it consumes all your CPU resources. In this case the program is blocked and uses close to no resources.
ask to enter numbers inside the loop,its easy to understand when to input particular number
int control = 1;
while (control <= 10)
{
cout << "Enter integer at position:"+Control << endl;
cin >> num;
if (num%2 == 0)
{
evenSum = evenSum + num;
}
else
{
oddSum = oddSum + num;
}
control++;
}
I could not see an error. Only the issue that you have to put 11 numbers instead of 10. Have you tried to type 11 numbers?
hey i am also a beginner but i tried to answer your question. you could also use compound assignment i.e. += instead of repeating evenSum and oddSum twice.
#include <iostream>
using namespace std;
int main()
{
int evenSum = 0;
int oddSum = 0;
int num;
int control = 0;
cout << "Enter 10 integers: " << "\n";
while (control <= 9 )
{
cin >> num;
if (num % 2 == 0)
{
evenSum += num;
}
else
{
oddSum += num;
}
control++;
}
cout << "The sum of the even integers is: " << evenSum << "\nThe sum of the odd integers is: " << oddSum << "\n";
return 0;
}

Need help in basic C++ regarding how to properly loop through part and finding smallest value

Hi I'm needing some help. I'm in a intro to programming class and we are using c++. I am hoping someone can help me with an assignment that was due yesterday (I understand not to expect miracle responses but a girl can always try).
I'm having two problems that I know of. The first is regarding the smallest value.
The big one is in trying to make it loop for requirements of three times but not lose out on my total count. I cannot use arrays or anything I haven't learned yet which is why I've posted this. I've seen similar problems and questions but they have ended up with answers too complex for current progress in class. So here is the problems instructions:
Instructions
1) Write a program to find the average value, the largest value, and the smallest value of a set of numbers supplied as input from the keyboard. The number of values in the data set must be in the range 0 to 20, inclusive. The user will first enter the number of values in the data set(use variable int Number). Give the user 3 attempts at entering Number in the range given. If the value for Number entered is out of this range, write an error message but continue. If the user does not enter a valid value for Number within the 3 attempts print an error message and terminate the program.
2) Format only the output for the Average value to 3 decimal places when printed.
3) The values in the data set entered as input can be any value positive, negative, or zero.
4) Make the program output readable(see the example below). (Note: that you will notprint out the input values that were entered in this program like you normally are required to do. This is because we have not covered the “tool” needed to do so yet in our studies).
Below will be the output from the execution of your program:
(using these values in order for the data set --> 19.0 53.4 704.0 -15.2 0 100.0)
The largest number: 704
The smallest number: -15.2
The average of the 6 numbers entered: 143.533
yourName L4p2XX.cpp
Lab#4 prob 2 XX-XX-12
Here is my poor excuse at the solution:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double Number = 0, minValue, maxValue, average, total = 0;
int ct = 0, numCount;
cout << "How many numbers would you like to enter? ";
cin >> numCount;
for(ct = 1; ct <= numCount; ct += 1)
{
cout << "Enter Value from 0 to 20, inclusive: ";
cin >> Number;
if(Number > 20|| Number < 0)
for(int errorCt = 1; errorCt <= 4; errorCt += 1)
{
if(errorCt == 4)
{
cout << "You have had 3 attempts to enter a valid" <<
"number. \nPlease try this program again when you" <<
"are able to follow directions.";
cout <<"\nLBn\n"<<"L4P2LB.cpp\n"<<"11-05-12\n";
return 0;
}
cout << Number << "is not within range.\n" <<
"Please enter a number from 0 to 20: ";
cin >> Number;
} //end for loop
total += Number;
if(maxValue <= Number)
maxValue = Number;
if(Number <= minValue)
minValue = Number;
} //end for loop
cout << "The smallest number entered was " << minValue << endl;
cout << "The largest number you entered was " << maxValue << endl;
average = total/numCount;
cout << setprecision(3) << fixed << showpoint << "You entered " <<
numCount << " numbers. The average of these is " << average;
//Program ID
cout <<"\n" << "L4P2LB.cpp\n" << "11-05-12\n";
system ("pause");
return 0;
} // End main
Thank you in advance to anyone who can steer me in the right direction. Not looking for anyone to do my work I just need help in direction if nothing else or any suggestions as to what to do. Thanks again. Lynda
Also I need somehow to pause after the third time and exit properly. If I put the second pause in it won't work so am I missing something obvious there too!
The first problem I see is that you didn't initialize a couple of variables.
You should either initialize both minValue and maxValue variables with something which will overwritten in every case in the first loop (typically "positive/negative infinity", as provided by <limits>), or just set both to Number in the first iteration, regardless of their current value. So I'd suggest to fix this by replacing
if(maxValue <= Number)
maxValue = Number;
if(Number <= minValue)
minValue = Number;
with
if(maxValue <= Number || ct == 1)
maxValue = Number;
if(Number <= minValue || ct == 1)
minValue = Number;
as ct == 1 will be true in the first iteration.
That said, you check the 0..20 range condition on the wrong variable. You check it on the Number variable, but you should check the numCount variable. But you also didn't respect the requirement that the variable to store the "number of numbers" should be Number, so you did check the correct variable, but used the wrong to read the input into. This should fix this issue (I changed the variable name in the cin >>... line + moved the check outside your main loop):
cout << "How many numbers would you like to enter? ";
cin >> Number;
if(Number > 20|| Number < 0)
{
for(int errorCt = 1; errorCt <= 4; errorCt += 1)
...
if(errorCt == 4)
{
cout << "You have had 3 attempts to enter a valid" <<
"number. \nPlease try this program again when you" <<
"are able to follow directions.";
cout <<"\nLBn\n"<<"L4P2LB.cpp\n"<<"11-05-12\n";
return 0;
}
cout << Number << "is not within range.\n" <<
"Please enter a number from 0 to 20: ";
cin >> Number;
} //end for loop
}
for(ct = 1; ct <= Number; ct += 1)
{
...
}
...

Is there a way to not include a negative number in an average, when entering a negative number is how you terminate the program?

Sorry about last time for those who saw my previous thread. It was riddled with careless errors and typos. This is my assignment:
"Write a program that will enable the user to enter a series of non-negative numbers via an input statement. At the end of the input process, the program will display: the number of odd numbers and their average; the number of even numbers and their average; the total number of numbers entered. Enable the input process to stop by entering a negative value. Make sure that the user is advised of this ending condition."
And here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number, total1=0, total2=0, count1=0, count2=0;
do
{
cout << "Please enter a number. The program will add up the odd and even ones separately, and average them: ";
cin >> number;
if(number % 2 == 0)
{
count1++;
total1+=number;
}
else if (number >= 0)
{
count2++;
total2+=number;
}
}
while (number>=0);
int avg1 = total1/count1;
int avg2 = total2/count2;
cout << "The average of your odd numbers are: " << avg1 << endl;
cout << "The average of your even numbers are " << avg2 << endl;
}
It seems to be working fine, but when I enter a negative number to terminate the program, it includes it with the rest of the averaged numbers. Any advice to get around this? I know it's possible, but the idea escapes me.
Your main loop should be like this:
#include <iostream>
for (int n; std::cout << "Enter a number: " && std::cin >> n && n >= 0; )
{
// process n
}
Or, if you want to emit a diagnostic:
for (int n; ; )
{
std::cout << "Enter a number: ";
if (!(std::cin >> n)) { std::cout << "Goodbye!\n"; break; }
if (n < 0) { std::cout << "Non-positve number!\n"; break; }
// process n
}
After here:
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
Immediately check if the number is negative
if(number < 0) break;
Now you wouldn't need to use your do-while loop in checking if the number is negative. Thus, you can use an infinite loop:
while(true) {
cout << "Please enter a number. The program will add up the odd and even ones seperately, and average them: ";
cin >> number;
if(number < 0) break;
// The rest of the code...
}
ADDITIONAL:
There is something wrong in your code. You aren't showing the user how much the number of even and odd numbers are, and the total number of numbers entered.
ANOTHER ADDITIONAL: You should use more meaningful variable names:
int totalNumEntered = 0, sumEven = 0, sumOdd = 0, numEven = 0, numOdd = 0;
Of course I am not limiting you to these names. You can also use other similar names.
FOR THE INTEGER DIVISION PROBLEM:
You must cast your expression values to the proper type (in this case, it is float). You should also change the averages variables' types to float:
float avg1 = float(total1) / float(count1);
float avg2 = float(total2) / float(count2);
Immediately after cin >> number, check for < 0, and break if so. Try to step through the program line by line to get a feel for the flow of execution. Have fun learning, and good luck!