Using Matlab 4.2 Number guessing Write code for a program that prompts the user
ID: 3902931 • Letter: U
Question
Using Matlab
4.2 Number guessing Write code for a program that prompts the user to enter a number between 0 and 10. If the user correctly guesses a number of your (the programmer's) own choosing, the program should display that they were suc- cessful. If not, you should prompt the user to try again until they are correct Extension . If the user enters a number outside of this range, remind them to only use numbers from 0 to 10 and try again Let the user know if their guess was higher or lower than the number If the user enters the same number twice in a row, let them know and prompt them to try again. If the user enters a sufficiently large negative number, exit the program and let them know they are a quitter. Only give the user a limited number of attempts. Be sure to let them know when they lose! Display how many guesses it took for the user to winExplanation / Answer
Given below is the code for the question.
Please do rate the answer if it was helpful. Thank you
disp('WELCOME TO GUESS-A-NUMBER');
n = randi([1 10], 1, 1); %generate a random integer from 1- 10
max_tries = 10;
disp('I am thinking of a number between 1 and 10');
disp('Guess the number I am thinking in a maximum of 10 trials');
guess = input('Make a guess: ');
tries = 1; %initialize number of tries to 1
%as long as some more tries are left
while(tries < max_tries)
if(guess > n)
fprintf('Too high! Try again ');
elseif(guess < n)
fprintf('Too low! Try again ')
else
break;
end
guess = input('Make a guess: ');
tries = tries + 1;
end
if( guess == n)
fprintf('You guessed my number %d and it took you %d tries! ', n, tries);
else
fprintf('You exceeded the max number of trials. The number was %d ', n);
end
output
====
WELCOME TO GUESS-A-NUMBER
I am thinking of a number between 1 and 10
Guess the number I am thinking in a maximum of 10 trials
Make a guess: > 5
Too low! Try again
Make a guess: > 8
Too low! Try again
Make a guess: > 9
You guessed my number 9 and it took you 3 tries!
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.