Can't exit the while loop after guessing the right number - c++

I'm trying to make a simple number guessing program with while loop but even after finding the right number (I changed the num with 5 and it didn't work) it does not exit the while loop. Can you tell me where the problem is?
int guess;
int num;
cout << "Enter the number (0-10): ";
cin >> guess;
while(guess != num){
int num = rand()%10;
cout << "Nope, keep trying." << endl;
cout << "Enter the number (0-10): ";
cin >> guess;
}
cout << "Congrats, you've found the number!" << endl;

int num = rand() % 10; is a declaration of a new variable num within the loop body and that shadows the num defined at the top of the program: while (guess != num) is using the latter.
The solution is to write num = rand() % 10; instead.
You will need to initialise num to a value before attempting to read it, else technically the behaviour of your program is undefined. Consider reworking to a do while loop.

The while loop is evaluating a num variable that is never assigned a value. The assignment being done inside the loop is to a different num variable that shadows the outer variable of the same name.
Try this instead:
#include <iostream>
#include <limits>
#include <cstdlib>
using namespace std;
int main() {
int guess;
int num;
do {
cout << "Enter the number (0-10): ";
if (cin >> guess) {
if (guess == num)
break;
num = rand() % 10;
cout << "Nope, keep trying." << endl;
}
else {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Not a number, keep trying." << endl;
}
}
while (true);
cout << "Congrats, you've found the number!" << endl;
}

Related

What loop should I use for the Question posted down below?

Question is how to get the program to ask for input until a valid choice (4-20) is given by the user? I just need to know how to repeat a question. So if a user inputs the wrong number then it will ask the user to input a valid number until the user enters a correct number between 4-20.
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main() {
int num; //integer for number
int roll; //integer for roll
srand(time(0)); //seed random number generator
cout << "You are about to roll a single die" << endl;
cout << "How many sided die would you like to roll(4-20)? ";
cin >> num;
cin.ignore();
roll = 1 + rand() % num; //mods random number
if (num >= 4 && num <= 20) {
cout << "You rolled: " << endl;
cout << roll << endl;
}
else
{
cout << "Please play again and enter a number between 4 and 20" << endl;
cout << "Press RETURN to continue..."<<endl;
cin.get();
cout<<"Exiting"<<endl;
}
return 0;
}
Try this
while(1)
{
cout << "Please enter a number between 4 and 20: ";
cin >> num;
if (num >= 4 && num <= 20)
{
//mods random number
//do something
break;
}
}
Do a while loop to keep on asking for input and have a if statement to break when it is between 4 and 20.

input validation in loop

I'm trying to make a validation loop in C++ that checks the user's input until they enter a number between 0 and 100 and however my loop only checks the first condition. Any guidance is appreciated!
#include <iostream>
using namespace std;
int main()
{
const int max_num = 100;
const int min_num = 0;
int num;
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
do {
if (!(cin >> num))
{
cout << "ERROR:The value provided was not a number" << endl;
cin.clear();
cin.ignore(1024, '\n');
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
}
else if (num<min_num || num>max_num)
{
cout << "ERROR: value out of range" << endl;
cin.clear();
cin.ignore(1024, '\n');
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
}
} while (!(cin >> num) || (num<min_num || num>max_num));
return 0;
}
Add lots of logging to your code so that you know what it's doing. This will help you find the problem. For example, instead of:
cout << "Enter a number between 0 and 100" << endl;
cin >> num;
Try:
cout << "Enter a number between 0 and 100" << endl;
cerr << "About to read into num outside the loop" << endl;
cin >> num;
cerr << "Read into num outside the loop, got: " << num << endl;
And so on, throughout your code. This should give you enough information to find the bug. Alternatively, use a debugger with a single step function to accomplish the same thing.
Check that in the part of while:
instead of
while (!(cin >> num) || (num<min_num || num>max_num));
this:
while (!cin || (num<min_num || num>max_num));
the same for the upper if
cin >> num means putting user input to the variable num . So you are trying to take user inputs 2 times in the loop. Maybe the check condition: (num == (int)num)will solve your problem. It will try to verify the number you have stored in num is really of the type int

C++ : Making a do while loop repeat

I'm very sorry for the super newbie question, but I cannot for the life of me understand how to make a do while loop repeat. I changed a while loop into a do while loop and now I don't know how to get it to ask "would you like to repeat Y or N?" any explanation?
I've read various posts that accomplish a do while loop repeat, but they don't make sense to me.
Am I essentially going to wrap this code into another do while loop? Do I move the boolean expression to before the while?
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans;
{
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
} while (count < N);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
system("pause");
return 0;
}
}
can do this:
char repeat='y';
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
for(int i=0;i<n;i++){
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
}
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>repeat;
}while(repeat=='y');
May be this is what you need, with char YorN you are considering if to continue or break the inner do-while.
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans;
char YorN;
do{
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++; //
} while (count < N);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
else {
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
}
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>YorN;
} while (YorN=='Y');
return 0;
}
Although there are a ton of ways to do it better, this code allows me to explain what is happening. Do-While loops are definitely pretty tricky. However, just remember that a do-while loop is designed to run at least once.
In the case of our code, we set up if statements to test against running code where it is not appropriate.
Take a look at how the very first if statement is N > 0, the if-statement does execute, please do not forget that. Once more for emphasis, the if statement DOES execute, it just results in false.
With that being said, you use a do-while loop when you want your code block to execute AT LEAST once. Notice how our while statement has two things we're testing for, one, is the answer 'Y' from the user to continue, and if it is, is the newly inputted N value greater than 0?
You might be wondering if the inner most if statement ever executes at least once, well the answer is it depends on the previous if statement result if(N > 0) and if(count == N && N != 0) both execute once every single time the while loop stays true. However that nested if depends on it's parent result.
I hope this cleared some things up for you on do-while loops.
#include <iostream>
using namespace std;
int main(void)
{
int x;
int count = 0;
int N;
double sum = 0;
double average;
char ans = 'Y';
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
do
{
if(N > 0){ //THIS IF STATEMENT WILL ALWAYS RUN AT LEAST ONCE
cout << "\n Enter a grade <Enter>: ";
cin >> x;
sum = sum + x;
count++;
}
if(count == N && N != 0) {//THIS IF STATEMENT WILL ALSO ALWAYS RUN AT LEAST ONCE
average = average = sum / N;
cout << "The average of these " << N << " grades is " << average << endl;
cout << "Would you like to enter more values to calculate your grade average?\n";
cin>>ans;
if(ans == 'Y') {//This one depends on it's parents result.
x = 0;
N = 0;
sum = 0;
count = 0;
cout << "Enter number of values, N, to be read in <Enter>:" << endl;
cin >> N;
}
}
} while (ans == 'Y' && N != 0);
if (N == 0)
cout << "You have entered 0 numbers. No average will be computed. Bye! \n";
system("pause");
return 0;
}

C++: While Looping Amount of Times

So I am trying to write a basic program that asks the user to input any number other than 5, and after 10 iterations of the user not entering the number 5, I want the program to print to screen.
Here is my code so far:
#include <iostream>
#include <string>
using namespace std;
int main(){
int num;
cout << "Please enter a number other than 5." << endl;
cin >> num;
while (num != 5){
cout << "Please enter a number other than 5." << endl;
cin >> num;
}
return 0;
}
I just don't know how to tell the computer to stop the loop at 10 iterations and output to the screen.
this is a suitable time to utilize the
do while
loop
the way it works is it will execute the statement within the block without evaluating any conditions and then evaluate the condition to determine if the loop should run again
this is what your program could look like
#include <iostream>
using namespace std;
int main(void)
{
int counter = 0, num;
do
{
if (counter > 10) // or >=10 if you want to display if it is 10
{
cout << "exiting the loop!" << endl;
break; // the break statement will just break out of the loop
}
cout << "please enter a number not equal to 5" << endl;
cin >> num;
counter++; // or ++counter doesn't matter in this context
}
while ( num != 5);
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main(){
int num;
int counter=1;
cin >> num;
cout <<num;
if(num==5)
cout << "Please enter a number other than 5." << endl;
while (num != 5&&counter<=10){
cin >> num;
cout <<num;
if(num==5)
cout << "Please enter a number other than 5." << endl;
counter=counter+1;
}
return 0;
}

Why the algorithm end after the first condition?

I'm designing a number guessing algorithm for use as a game.
Can anyone suggest why does the algorithm end after the first condition?
#include <iostream>
using namespace std;
int main()
{
int num = 5;
int guess;
cout << "Guess a number \n";
cin >> guess;
if (guess==num)
{
cout << "You guessed the correct number \n";
}
else if (guess < num)
{
cout << "Your guess is lower than the number \n";
cout << "Guess again \n";
cin >> guess;
}
else
{
cout << "Your guess is higher than the number \n";
cout << "Guess again \n";
cin >> guess;
}
return 0;
}
You need some kind of loop if you want that the algorithm would be repeated.
For example
#include <iostream>
using namespace std;
int main()
{
int num = 5;
int guess;
cout << "Guess a number \n";
do
{
cin >> guess;
if ( guess == num )
{
cout << "You guessed the correct number \n";
}
else if ( guess < num )
{
cout << "Your guess is lower than the number \n";
cout << "Guess again \n";
}
else
{
cout << "Your guess is higher than the number \n";
cout << "Guess again \n";
}
} while ( guess != num );
return 0;
}
If you wish to guess again I'd recommend a loop. Otherwise your code works as intended.
while(number != guess)
{
if(number * 2 < guess){
cout << "Way to high. Try again." << endl;
cin >> guess;
}
if(number / 2 > guess)
{
cout << "Tip : My number is NOT low. Try again." << endl;
cin >> guess;
}
if(number < guess)
{
cout << "To high try something lower. Feed me a number." << endl;
cin >> guess;
}
if(number > guess)
cout << "To low, try again." << endl;
cin >> guess;
}