If Else in Scilab
Branching with if
and else
in Scilab is straightforward.
// Here's a basic example.
if modulo(7, 2) == 0 then
disp("7 is even")
else
disp("7 is odd")
end
// You can have an `if` statement without an else.
if modulo(8, 4) == 0 then
disp("8 is divisible by 4")
end
// Logical operators like `&` and `|` are often useful in conditions.
if modulo(8, 2) == 0 | modulo(7, 2) == 0 then
disp("either 8 or 7 are even")
end
// A statement can precede conditionals; any variables
// declared in this statement are available in the current
// and all subsequent branches.
num = 9;
if num < 0 then
disp(num + " is negative")
elseif num < 10 then
disp(num + " has 1 digit")
else
disp(num + " has multiple digits")
end
Note that in Scilab, you don’t need parentheses around conditions, but the then
keyword is required. The end
keyword is used to close the if
block.
To run this script, save it as if_else.sce
and execute it in Scilab:
--> exec('if_else.sce', -1)
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit
There is no ternary operator in Scilab, so you’ll need to use a full if
statement even for basic conditions.
Scilab uses &
for logical AND and |
for logical OR, unlike some other languages that use &&
and ||
. Also, string concatenation in Scilab is done using the +
operator.
The modulo
function is used in place of the %
operator for remainder calculations. The disp
function is used for displaying output, similar to print
or console.log
in other languages.
Scilab’s elseif
is written as one word, unlike the else if
in some other languages.
These differences showcase some of the unique aspects of Scilab’s syntax and built-in functions compared to other programming languages.