CS112: Lab 6 :: Functions and loops
Task 1a. A guessing game
Write a script called playGuess to play a guessing game with the user. Your loop will keep asking for 7 guesses until the user either 1) guesses correctly, 2) quits or 3) runs out of guesses. Sample output is shown below.Hints:
- randi([1,100]) generates a random integer between 1 and 100, inclusive.
- input('Guess the secret number (q to quit) ==> ','s') allows for string input
- Think about the different ways the game can end and how to handle those cases.
Example 1: the secret number is 1 and the user quits (by typing 'q') >>playGuess Guess the secret number (q to quit) ==> 50 Too high Guess the secret number (q to quit) ==> 12 Too high Guess the secret number (q to quit) ==> 5 Too high Guess the secret number (q to quit) ==> q bye! Example 2: the secret number is 73 and the user wins in 3 guesses. >>playGuess Guess the secret number (q to quit) ==> 50 Too low Guess the secret number (q to quit) ==> 75 Too high Guess the secret number (q to quit) ==> 73 Wahooo! You won in 3 guesses Example 3: the secret number is 47 and the user runs out of guesses >>playGuess Guess the secret number (q to quit) ==> 80 Too high Guess the secret number (q to quit) ==> 75 Too high Guess the secret number (q to quit) ==> 60 Too high Guess the secret number (q to quit) ==> 50 Too high Guess the secret number (q to quit) ==> 40 Too low Guess the secret number (q to quit) ==> 45 Too low Guess the secret number (q to quit) ==> 46 Too low Sorry, you used all 7 of your guesses.
Task 1b. Create a function called guessMyNumber
Create a new MATLAB file with the name guessMyNumber
.
Building from the contents of the playGuess
script above,
create a function that has an optional input (the maximum number of guesses).
If the user does not supply an argument, the default guess limit is 7.
>> guessMyNumber(1) Guess the secret number (q to quit) ==> 25 Too low Sorry, you used all 1 of your guesses. >> guessMyNumber(3) Guess the secret number (q to quit) ==> 50 Too low Guess the secret number (q to quit) ==> 75 Too high Guess the secret number (q to quit) ==> 62 Too low Sorry, you used all 3 of your guesses. >> guessMyNumber() Guess the secret number (q to quit) ==> 50 Too low Guess the secret number (q to quit) ==> 75 Too high Guess the secret number (q to quit) ==> 60 Too high Guess the secret number (q to quit) ==> 57 Too low Guess the secret number (q to quit) ==> 58 Too low Guess the secret number (q to quit) ==> 59 Wahooo! You won in 6 guesses