Cannot find my infinite loop

Joined
Sep 12, 2023
Messages
1
Reaction score
0
This says it is producing an infinite loop, but i cant find where

#include <iostream>
using namespace std;
int main ()
#include <cstdlib>

{


char y = 'y';
char n = 'n';
char LikeToPlay;
int Guess;

cout << "Would you like to play? (enter y or n)" << endl;
cin >> LikeToPlay;



while (LikeToPlay == y)
{

int RandomNumber;
srand (99);
RandomNumber = rand() % 10 + 1;

cout << "Enter your guess" << endl;
cin >> Guess;


if (Guess > RandomNumber){
cout << "Your guess is greater than the random number." << endl; }
else if (Guess < RandomNumber){
cout << "Your guess is less than the random number." << endl; }
else if (Guess == RandomNumber){
cout << "Congratulations. You guessed correctly." << endl;

cout << "Would you like to play again? (enter y or n)" << endl;
cin.ignore();
cin >> LikeToPlay;
}
}


if (LikeToPlay != y)
{cout << "Thanks for playing. Come back again." << endl;
}
return 0;
}
 
Joined
Jul 4, 2023
Messages
356
Reaction score
41
Check this ... your code slightly improved
C++:
#include <iostream>
#include <ctime>
using namespace std;

int main ()
{
    char y = 'y';
    char LikeToPlay;
    int Guess = 0;
   
    srand(time(nullptr));

    cout << "Would you like to play? (enter y or n)" << endl;
    cin >> LikeToPlay;

    while (LikeToPlay == y)
    {
        int RandomNumber = 0;
        RandomNumber = rand() % 10 + 1;

        cout << "Enter your guess" << endl;
        cin >> Guess;


        if (Guess > RandomNumber)
        {
            cout << "Your guess is greater than the random number." << endl;
        }
        else if (Guess < RandomNumber)
        {
            cout << "Your guess is less than the random number." << endl;
        }
        else if (Guess == RandomNumber)
        {
            cout << "Congratulations. You guessed correctly." << endl;
        }

         // this part, out of last "if" statement
        cout << "Would you like to play again? (enter y or n)" << RandomNumber << endl;
        cin.ignore();
        cin >> LikeToPlay;
       
        if (LikeToPlay != y)
        {
            cout << "Thanks for playing. Come back again." << endl;
        }
    }

    return 0;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top