MATLAB: Guessing game help (beginner programmer)

guessing gameoctavewhilewhile loopwhile loops

I need to create a guessing game program using while loops where the user needs to guess between 1 and 10 and they only get three tries. every time they get it wrong a message will display that their guess is wrong and to re enter another number. if its correct they will get a "right!" display but if they guess correct and tries exceeded 3 times a message will display that they got the right number but they exceeded tries and lost the game.
this is the program i have created so far and im stuck on the little things like how do i generate the program so that it allows 3 tries before you lose. this program might be a bit mixed up.
secretnumber = randi([1 10]);
numguesses = 0;
disp('I am thinking of a number from 0 to 10.');
disp('You must guess what it is in three tries.');
guess = input('Enter a guess: ');
while guess ~= secretnumber
numguesses = numguesses + 1;
if numguesses == secretnumber
disp('Right!');
fprintf('it took you %g guesses. You have won the game!');
end
endwhile

Best Answer

Reila01 - this sounds like this guessing game could be homework. I think that you have the correct pieces of the code, just not necessarily all in the correct place. For example, if the user incorretly guesses the secret number, then you need to prompt him or her to try again. This suggests that the input prompt should be inside your while loop. The condition
if numguesses == secretnumber
is incorrect, since you are not comparing the number of guesses with the secret number, but the guess (the result from the input prompt) with the secrent number. Further if this is true, then you can compare the numguesses with 3 - if 3 or less, then display the "correct!" message. If it took more than three guesses, then display the "correct but you still lose" message. As the user has guessed the answer (for how many guesses it took), then you will want to break out of the while loop since (though I guess the condition on the while loop will take care of this). Also, if you want to print the number of guesses that it took
fprintf('it took you %g guesses. You have won the game!');
you need to include the variable as a parameter input to fprintf (and use %d for an integer output)
fprintf('it took you %d guesses. You have won the game!', numguesses);
Related Question