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

35 views (last 30 days)
Trisha Katz on 29 Oct 2019
Commented: Trisha Katz on 29 Oct 2019
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!

#### 1 Comment

SATHISH KUMAR M on 29 Oct 2019
u can use IF loop to get ur answer......
but in here i think u have to use "BREAK" to stop infinite loop

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

#### 1 Comment

Trisha Katz on 29 Oct 2019
This did not work

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