How do I get execute while else loop?
93 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
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"
0 Comments
See Also
Categories
Find more on Geometric Transformation and Image Registration 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!