Using else
we can perform some task when the condition is not satisfied. But what if we want to check a second condition in case that the first one was false. We can do it this way:
a = 9;
if mod(a,2)==0 % MOD - modulo operation, return the remainder after division of 'a' by 2
disp('a is even')
else
if mod(a,3)==0
disp('3 is a divisor of a')
end
end
OUTPUT:
3 is a divisor of a
This is also called "nested condition", but here we have a speciel case that can improve code readability, and reduce the chance for anr error - we can write:
a = 9;
if mod(a,2)==0
disp('a is even')
elseif mod(a,3)==0
disp('3 is a divisor of a')
end
OUTPUT:
3 is a divisor of a
using the elseif
we are able to check another expression within the same block of condition, and this is not limited to one try:
a = 25;
if mod(a,2)==0
disp('a is even')
elseif mod(a,3)==0
disp('3 is a divisor of a')
elseif mod(a,5)==0
disp('5 is a divisor of a')
end
OUTPUT:
5 is a divisor of a
Extra care should be taken when choosing to use elseif
in a row, since only one of them will be executed from all the if
to end
block. So, in our example if we want to display all the divisors of a
(from those we explicitly check) the example above won't be good:
a = 15;
if mod(a,2)==0
disp('a is even')
elseif mod(a,3)==0
disp('3 is a divisor of a')
elseif mod(a,5)==0
disp('5 is a divisor of a')
end
OUTPUT:
3 is a divisor of a
not only 3, but also 5 is a divisor of 15, but the part that check the division by 5 is not reached if any of the expressions above it was true.
Finally, we can add one else
(and only one) after all the elseif
conditions to execute a code when none of the conditions above are met:
a = 11;
if mod(a,2)==0
disp('a is even')
elseif mod(a,3)==0
disp('3 is a divisor of a')
elseif mod(a,5)==0
disp('5 is a divisor of a')
else
disp('2, 3 and 5 are not divisors of a')
end
OUTPUT:
2, 3 and 5 are not divisors of a