I am trying to create a game where a user guesses a number between 1 and 100 using a while loop. But I am getting stuck in an infinite loop. Please help?

36 views (last 30 days)
Here is what I have:
y=randi(1,100)
prompt= 'guess a value between 1 and 100'
x=input(prompt)
while x<y
disp('guess higher')
(strfind(question,checkExit))
end
while x>y
disp('guess lower')
end
while x==y
disp('you win')
end
So, the computer correctly generates a random value, but when I guess it, it gets stuck in an infite loop of guess lower guess lower guess lower etc. How do I stop this? Thanks!

Answers (3)

galaxy
galaxy on 29 Oct 2019
Let 's try
y=randi(100);
while (1)
prompt= '\nguess a value between 1 and 100: ';
x=input(prompt);
if (x<y)
disp('guess higher');
elseif (x>y)
disp('guess lower');
else
disp('you win');
break;
end
end
  5 Comments
Muhammad Waheed AZAM
Muhammad Waheed AZAM on 26 Oct 2022
this code always give 82 number is correct can you help me to improve please
x=randi(100);
y=input(number);
while (1)
number='guess the number between 1 and 100=';
if (y>x)
disp('your guess is higer');
elseif (y<x)
disp('your guess is lower');
else
disp('your guess is correct');
break;
end
end

Sign in to comment.


Image Analyst
Image Analyst on 26 Oct 2022
Try this:
trueNumber = randi(100);
userPrompt = 'Guess the number between 1 and 100 : ';
maxGuesses = 7;
numGuesses = 0;
usersGuess = input(userPrompt);
while numGuesses < maxGuesses
if (usersGuess > trueNumber)
fprintf(' Your guess of %d is too high.\n', usersGuess);
elseif (usersGuess < trueNumber)
fprintf(' Your guess of %d is too low.\n', usersGuess);
elseif usersGuess < 0
break; % Quit if they enter a negative number or try more than 6 times.
else
fprintf(' Your guess is %d is correct.\n', usersGuess);
break;
end
numGuesses = numGuesses + 1;
% Let them try again
userPrompt = sprintf('Attempt #%d. Guess the number between 1 and 100 : ', numGuesses);
usersGuess = input(userPrompt);
end

Bhaskar R
Bhaskar R on 29 Oct 2019
Here you have made some mistakes
1) Gerenating vector instead of single random number
y=randi(1,100); % Which generates the 1x100 vector not a single random number
Here use single interger random value as
y = randi(100); % correct way to get a random value between 1, 100(100 is max limit value)
2) While loops
What is the need to use while loop, you can go with if else condition
If necessory, put break keyword in each while loop.
3) comparing single user input value x to y vector in while loop condition checking

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!