MATLAB: Random numbers between 1 and 10 with limited attempts

limited attemptsrandom number

Hello
I haven't found anything by searching this site, on the other hand I am new to this. I really would appreciate it if you could help me out on this one: I try to make a program which selects a random number between 1 and 10. One gets a limited amount of attempts to guess the right number. After 5 attempts, the programm should stop and tell you that you didn't succeed. I wrote some code and it does everything except stopping when one guessed the right number before attempt 5.
I tried changing everything but I only ended up in an infinite loop, after two hours I really would like to get help. 😀
This is what I wrote:
Pickme=round(10*rand(1)); %Pick random number between 1 and 10
Guessedcorrectly=0;
while Guessedcorrectly == 0 %As long as the correct number has not been picked
for i=1:5
A(i)=input('Enter a number between 1 and 10:');% ask for new input
if A(i) == Pickme %Check whether number is correct
Guessedcorrectly = 1; %if so, have while-loop stop
disp('Correct! You have picked the right number!') %print message on screen
else disp('Wrong! Try again.') %if not, print on screen
end
end
end
The preview tells me that after for i=1:5, all this is put in a code/quote. I don't know why it does that. Can someone help me with my problem, i.e. why doesn't the script stop after one guessed the right number?
Greetings,
Keeks

Best Answer

The script doesn't stop because it wants to finish the for-loop first. It will not check the line 'while Guessedcorrectly == 0' until the for-loop is done. There are many ways to solve this issue, but perhaps the easiest is to amend your code as follows:
...
if A(i) == Pickme %Check whether number is correct
Guessedcorrectly = 1; %if so, have while-loop stop
disp('Correct! You have picked the right number!') %print message on screen
break; % this tells MATLAB to leave the for-loop
...