How to check two conditions?

How can I check two conditions in if and elseif statment? When I run the following code, I got the last sentence " Your input is negative and even number "
function output=even_or_odd(n)
n = 'Insert a number: ';
x = input(n);
if x>=0 & rem(n,2)==0
disp('Your input is positive and even number ');
elseif x>=0 & rem(n,2)~=0
disp('Your input is positive and odd number ');
elseif x<0 & rem(n,2)==0
disp('Your input is negative and even number ');
else
disp('Your input is negative and even number ');
end
end

 Accepted Answer

function output=even_or_odd()
x = input('Insert a number: ');
if mod(x,2)==0&&x>=0
output='Your input is positive and even number';
elseif mod(x,2)==1&&x>=0
output='Your input is positive and odd number';
elseif mod(x,2)==0&&x<0
output='Your input is negative and even number';
else
output='Your input is negative and odd number';
end
end

5 Comments

Thank you so much. I tried to use && insted of & but I got an error .
% Operands to the || and && operators must be convertible to logical scalar values
I just have question. is it wrong to write x<=0 before rem(x,2)==0?
No, either way
@Omar B. You'll get that error if you use && or || on non-scalars (i.e., vectors, matrices). Is your code supposed to work for non-scalar inputs or just scalars?
I am working with just scalars. In my code I used & not &&.
Thank you so much. I got it.

Sign in to comment.

More Answers (0)

Categories

Asked:

on 9 Feb 2022

Commented:

on 11 Feb 2022

Community Treasure Hunt

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

Start Hunting!