How to stop a while loop when 'N' is entered

16 views (last 30 days)
This is what I have so far, I would like for the code to stop when the user types 'N', but instead the program keeps repeating, how do I fix this? I have attached a picture of the original problem as well.
% code
while 'Y'
input('Choose any positive number to compute the factorial of: ')
n = ans;
f = factorial(n);
if ans > 0
fprintf('The factorial is: %d\n', f)
end
input('Do you wish to enter an additional value? Y/N: ','s')
end

Answers (1)

Geoff Hayes
Geoff Hayes on 18 Apr 2014
Hi Samantha,
Your while loop will run forever as it is not dependent upon any variable, only on the fixed constant 'Y' (which is nonzero). I think that you need to capture the user response of your final input command when you ask the user whether to continue or not:
resp = input('Do you wish to enter an additional value? Y/N: ','s');
Then compare this response to 'N' or 'n' as and act accordingly:
if strcmpi(resp,'n')
% user has typed in N or n so break out of the while loop
break;
end
The strcmpi function ignores the case (upper or lower) of 'N' so you needn't check for either 'N' or 'n'…just the one will do.
Hope the above helps!
Geoff

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!