How do I get execute while else loop?

22 views (last 30 days)
Steven Tan
Steven Tan on 17 Jun 2021
Edited: Jan on 18 Jun 2021
Hello. I am trying to create a loop that when userinput == 'yes' for the question to continue, it will run the questions. But if the userinput == 'no', I want it to print 'Thank you'.
I am having trouble to get the code to execute the part when userinput == 'no'.
answer = 'yes';
if answer == 'yes'
while (answer == 'yes')
dia = input('Enter the circle diameter : ');
choice = input('Enter your choice : ');
if choice == 1
area = pi * (dia/2)^2;
fprintf('Area of circle = %.1f \n', area);
elseif choice == 2
circum = pi * dia;
fprintf('Circumference of circle = %.1f \n', circum);
else
fprintf('Invalid choice \n');
end
answer = input('Do you want to continue? [yes/no] : ', 's');
end
else
fprintf('Thank you');
end

Answers (1)

Jan
Jan on 17 Jun 2021
Edited: Jan on 18 Jun 2021
The == operator compares its arguments elementwise. This works only if one of the array is a scalar or if bother have the same size.
Use strcmp to compare CHAR vectors. The == operator works with strings:
answer = 'yes';
if strcmp(answer, 'yes')
while strcmp(answer, 'yes')
Or
answer = "yes"; % Double quotes!
if answer == "yes"
while answer == "yes"

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!