Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The user gets 3 tries to guess the lucky number (set the lucky number =4) Write

ID: 3782103 • Letter: T

Question

The user gets 3 tries to guess the lucky number (set the lucky number =4) Write generalized code (i.e. if I want to change the lucky number value, I change it at only one location within the program) The user is prompted to enter a number between 1 and 10 The entered number is compared to the lucky number, if it is equal to the lucky number, tell the user that they guessed the correct number, if not tell them to guess again. After each guess, tell them how many guesses they have left. Store all the user guesses in a matrix called 'user_guesses'. At the end of the game display the numbers guessed by the user. The user gets as many tries as required to guess the lucky number (set the lucky number =4) Write generalized code The user is prompted to enter a number between 1 and 10 The entered number is compared to the lucky number, if it is equal to the lucky number, tell the user that they guessed the correct number, if not tell them to guess again. When they eventually guess the correct number, tell them how many tries it took them to guess the correct number.

Explanation / Answer

Following is the program written in MATLAB

%Initializing the lucky number,
lucky_number = 4;

%Initializing user_attempts to store count of user attemtps of guesses in the game
user_attempts = 0;

%Initializing maximum allowed guesses to max_allowed_attempts
max_allowed_attempts = 3;

%function which prompts user for a input number between 1 and 10
%and checks whether the guess is equal to the lucky number and if not
%then asks the user to guess again

function x = inputAndCompare()
   if(user_attempts == max_allowed_attempts)
       disp('you have reached your maximum allowed attempts');
       disp(user_guesses);
       return;
   end
   prompt = "Input a number between 1 and 10"
   input_num = input(prompt)
   if(input_num == lucky_number)
       disp('you have guessed correctly about the lucky number');
   else
       disp(your guess is incorrect and hence you can guess again');
       user_guesses(0,user_attempts) = input_num;
       user_attempts = user_attempts+1;
       inputAndCompare();
   end  
end

inputAndCompare();