how to ask a for input, and keep asking the same question until the right input is inputted?

13 views (last 30 days)
If I want the user to input an even number, and keep asking the user to input another number if they input an odd number or zero.
  3 Comments
Man Hon Morrison Kong
Man Hon Morrison Kong on 19 Jan 2019
x = input('Please, input an even number ')
if x==0
disp('This number is zero,please rerun the programme again,sorry this is not automatic')
elseif mod(x,2) == 0
disp('the number is even')
else
disp('This is an odd number,please rerun the programme again,sorry this is not automatic')
end
%this is what I did, but I dont know how to put it into a while loop.

Sign in to comment.

Accepted Answer

per isakson
per isakson on 20 Jan 2019
Edited: per isakson on 20 Jan 2019
One way. n avoids running forever.
%%
n = 0;
while n <= 12
n = n + 1;
x = input('Please, input an even number ');
if x==0
disp('This number is zero, please rerun the programme again, sorry this is not automatic')
elseif mod(x,2) == 0
disp('the number is even')
break
else
disp('This is an odd number, please rerun the programme again, sorry this is not automatic')
end
end

More Answers (0)

Categories

Find more on Function Creation in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!