Nested While loop functions

Given: I have created a simple number guessing game that prompts the user to guess a random number between 1 & 100 and will inform them if their guess is too high or too low, then tell them when they have guessed right.
Find: I need to find a way to use another while loop, (either inside of or side by side), to ask the user if they would like to play again after they have guessed the right answer.
Issue: I just don't even know where to begin. I got the first loop running smooth, but I am unsure of how to use another loop to loop that loop if prompted to do so by the user.
My Solution: I didn't suppress the output of num so I can troubleshoot the code.
num=randi([1,100])
guess=input('Welcome to the game! Guess a number between 1 & 100: ');
count=1;
while num~=guess
count=count+1;
if guess>100 || guess<1
disp('Invalid Entry')
elseif guess>num
disp('Your guess is too high')
else
disp('Your guess is too low')
end
guess=input('Enter a new number: ');
end
disp('You guessed right! What a surprise!')
fprintf('You guessed this many times: %i\n',count)
if count==1
disp('You cheated!')
elseif count<4
disp('Not bad.')
else
disp('Practice makes perfect...')
end
% My thinking is to somehow put my working "game" into another while loop
% and ask the user to input a 1 if they want to play again, or a 2 if not, but how would I do
% that? while r,(response)=1,(yes)? This would be my first nested loop.

12 Comments

I think your idea to wrap this code in another while loop wherein the user is asked whether they want to play again is a good approach.
Try it out and see what happens. If you get stuck, post your updated code.
VBBV
VBBV on 8 Apr 2024
Edited: VBBV on 8 Apr 2024
Hint: @Kyle Weaver Use of defining custom functions is better in this context and call the function inside another while loop
@VBBV, I can kind of envision what you're talking about... I am not sure how to do this as I am simply practicing with while loops in a script, not a seperate function file. From my experience, using a defining custom function is it's own file, that is called using the filename. Am I thinking of the same thing?
while x~=1
x=input('Do you want to play again? (y)1 (n)2: ');
if x==1
guess=input('Welcome to the game! Guess a number between 1 & 100: ');
else
disp('Have a nice day!')
end
% num=randi([1,100]);
% guess=input('Welcome to the game! Guess a number between 1 & 100: ');
% count=1;
% while num~=guess
% count=count+1;
% if guess>100 || guess<1
% disp('Invalid Entry')
% elseif guess>num
% disp('Your guess is too high')
% else
% disp('Your guess is too low')
% end
% guess=input('Enter a new number: ');
% end
% disp('You guessed right! What a surprise!')
% fprintf('You guessed this many times: %i\n',count)
%
% if count==1
% disp('You cheated!')
% elseif count<4
% disp('Not bad.')
% else
% disp('Practice makes perfect...')
% end
end
Ok gents, here is where my head is at. I'm pretty toilworn from the day. There's still some work to be done here but I will tackle this problem with a fresh set of eyes. I commented the working code and need to figure out the rest.
VBBV
VBBV on 8 Apr 2024
Edited: VBBV on 8 Apr 2024
@Kyle WeaverThe answer to this question is present in your question. Make the loops nested (one within another)
while 1 % repeat the whole thing till the user wants to quit
x=input('Do you want to play again? (y)1 (n)2: ');
if x==1
guess=input('Welcome to the game! Guess a number between 1 & 100: ');
num=randi([1,100]);
count=1;
while num~=guess
count=count+1;
if guess>100 || guess<1
disp('Invalid Entry')
elseif guess>num
disp('Your guess is too high')
else
disp('Your guess is too low')
end
guess=input('Enter a new number: ');
end
disp('You guessed right! What a surprise!')
fprintf('You guessed this many times: %i\n',count)
if count==1
disp('You cheated!')
elseif count<4
disp('Not bad.')
else
disp('Practice makes perfect...')
end
else
disp('Have a nice day!')
break % give a break if the user wants to quit
end
end
Genius! This is perfect. I just wasn't sure how to nest them together I suppose. I am unfamiliar with the break function as it relates to loops. I'm assuming it simply 'breaks' the loop?
That's right: break stops execution of the for or while loop it's located in; execution resumes after the loop's end statement.
If you wanted to break out of multiple nested loops at once, you'd need to create a variable that tells the program whether to break out of the outer loops or not. Example:
do_break_all = false;
while true
while true
while true
x = rand();
if x < 0.01
do_break_all = true;
break
end
end
if do_break_all
break
end
end
if do_break_all
break
end
end
Wow. That's a lot of loops. The more I learn about coding the harder it seems to be something I can master.
All right. Forget about that example then.
It was an amazing example. Sometimes it's just hard visualizing where one loop starts and one ends.
That's what indentation is for. Each "end" lines up with its corresponding while/for/if.
It still hurts my brain, lol.

Sign in to comment.

 Accepted Answer

Hi Kyle,
To achieve the functionality of asking the user if they want to play the game again after they've guessed the number correctly, you can indeed use another while loop around your existing game loop. This outer loop will control whether the game restarts based on the user's input. Here's how you can structure it:
  1. Initialize a variable before the outer loop to control whether the game should continue. Let's call this variable playAgain and set it to true initially.
  2. Wrap your existing game code inside this outer while loop, which continues as long as playAgain is true.
  3. After the inner game loop (where the user has guessed the number correctly), prompt the user to ask if they want to play again.
  4. Based on the user's input, update the playAgain variable. If the user chooses to play again, the outer loop will continue; otherwise, it will exit, ending the game.
Here's how your code could look with these modifications:
playAgain = true; % Initialize the play again control variable
while playAgain
num = randi([1,100]); % Generate a random number
fprintf('Welcome to the game! Guess a number between 1 & 100: ');
guess = input('');
count = 1;
while num ~= guess
count = count + 1;
if guess > 100 || guess < 1
disp('Invalid Entry');
elseif guess > num
disp('Your guess is too high');
else
disp('Your guess is too low');
end
guess = input('Enter a new number: ');
end
disp('You guessed right! What a surprise!');
fprintf('You guessed this many times: %i\n', count);
if count == 1
disp('You cheated!');
elseif count < 4
disp('Not bad.');
else
disp('Practice makes perfect...');
end
% Ask the user if they want to play again
playAgainResponse = input('Do you want to play again? (yes=1/no=0): ');
if playAgainResponse == 1
playAgain = true; % User wants to play again
else
playAgain = false; % User does not want to play again, exit the loop
end
end
disp('Thanks for playing!');
In this code, after the user successfully guesses the right number, they are prompted to decide whether they want to play again. If the user inputs 1, the game restarts. If they input 0, the message 'Thanks for playing!' is displayed, and the program exits the outer loop, effectively ending the game. This approach allows for the game to be played multiple times without restarting the script manually.
I hope this helps!

1 Comment

Eureka! This helped so much! I knew what I wanted to do but not quite how to go about it! Any idea how I would calculate the AVERAGE of all the guesses across all of the games played and then display then after the user has decided they no longer want to play? Thank you so much :)

Sign in to comment.

More Answers (0)

Categories

Find more on Board games in Help Center and File Exchange

Products

Release

R2024a

Tags

Asked:

on 8 Apr 2024

Commented:

on 16 Apr 2024

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!