MATLAB Answers

0

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

Asked by Man Hon Morrison Kong on 17 Jan 2019
Latest activity Edited by per isakson
on 20 Jan 2019
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

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.

Tags

1 Answer

Answer by per isakson
on 20 Jan 2019
Edited by per isakson
on 20 Jan 2019
 Accepted Answer

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

  0 Comments

Sign in to comment.