Write the MATLAB code to create a guessing game. Your code must do all or the fo
ID: 3804938 • Letter: W
Question
Write the MATLAB code to create a guessing game. Your code must do all or the following: a. Prompt the user for their choice of upper bound (largest positive integer). Continue prompting until the user provides a valid value. b. Randomly generate a target integer (the number to be guessed) between -10 and the user's choice of upper bound. c. Embed the user's upper bound in the "guess" prompt. d. Keep track of number of guesses and report that number after the guess is correct. e. Use variable names that suggest their meaning. Here is a sample run of the game: Welcome to my Guessing Game! The smallest integer will be -10. What shall I set for the largest positive integer? 1.7 Sorry, we need a positive integer: -3 Sorry, we need a positive integer: 15 Okay, let's begin: Guess an integer between -10 and 15: 3 Too small! Guess an integer between -10 and 15: 14 Too big! Guess an integer between -10 and 15: 12 Too big! Guess an integer between -10 and 15: 10 Correct! It took you 4 guesses.Explanation / Answer
fprintf('Welcome to my Guessing Game! ');
fprintf('The smallest integer will be -10. ')
upperLimit = input("What shall I set for the largest positive integer? ");
while upperLimit <0 || round(upperLimit)~=upperLimit
upperLimit = input("Sorry, we need a positive integer: ");
end
guess = randi(upperLimit + 11)-11;
flag = false;
count = 0;
while ~flag
count = count +1;
fprintf('Guess a Integer between -10 and %d',upperLimit);
userGuess = input(': ');
if (userGuess < guess)
fprintf('Too low ');
continue;
end
if (userGuess > guess)
fprintf('Too high ');
continue;
end
fprintf('correct ');
flag = true;
end
fprintf('It took you %d guesses ',count)
NOTE: I have not commented the code since it was instructed in the question. If you need explanation, pls comment below. Hope you like the solution
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.