I wrote a program that is basically a jumble. It scrambles a word, and the user has ten guesses to get it right. The loop ends when the user hits ten guesses, or gets it right. If works perfectly now, but I can’t help but thinking there is a better way to do it. Here’s the code:
%Now we enter the loop, which will end when the user either correctly
%identifies the word, or has made ten incorrect guesses
loop_end = 0;
while loop_end == 0
%We display the number of guesses the user has taken
fprintf('You have used %d guesses
', numguess)
%We increment the number of guesses by 1
numguess = numguess + 1;
%We then prompt the user for their next guess
fprintf('
Guess #%d', numguess)
guess = input(': ', 's');
%We use strcmp to see if the guess matches the correct word. A 1 will
%be stored in correct_guess if they do, a 0 will be stored if they
%don't
correct_guess = strcmp(guess, correct_word);
%We then use an if statement. If correct_word is 1, a message is
%displayed, and the loop will end.
if correct_guess == 1
fprintf('Congratulations! That''s correct! You win!
')
%we also change the loop_end variable to 1, so that the loop will
%end
loop_end = 1;
%If correct_word is a 0, a message is displayed saying it is wrong
else
fprintf('I''m sorry, that''s incorrect.
')
end
%We now check to see if the user has guessed 10 times. If they have,
%loop_end is changed to 1 and the loop will end.
if numguess == 10
loop_end = 1;
end
end
As you can see, I use the variable loop_end to tell the loop when to end. I know there must be a way to simply put the conditions I need to end the loop in the while statement itself using the or function (||) but I couldn’t get it to work. It just seems like this won’t be considered to be the best way to do this.