The Xcas language has different ways of writing if…then statements (see Section 6.1.3). The standard version of the if…then statement consists of the if keyword, followed by a boolean expression (see Section 6.1) in parentheses, followed by a statement block (see Section 12.1.7) which will be executed if the boolean is true. You can optionally add an else keyword followed by a statement block which will be executed if the boolean is false:
(where recall the blocks need to be delimited by braces or by begin and end).
Examples.
a:=3; b:=2:; |
if (a > b) { a:= a + 5; b:= a - b;}:; |
a,b |
8,6 |
a:=3; b:=2:; if (a < b) { a:= a + 5; b:= a - b;} else { a:=a - 5; b:= a + b;}:; a,b |
−2,0 |
An alternate way to write an if statement is to enclose the code block in then and end instead of braces:
Examples.
a := 3 |
if (a > 1) then a:= a + 5; end |
8 |
a:=8 |
if (a > 10) then a:= a + 10; else a:= a - 5; end |
3 |
Several if statements can be nested; for example, the statement
A simpler way is to replace the else if by elif and combine the ends; the above statement can be written
In general, such a combination can be written
if (boolean 1) then |
block 1; |
elif (boolean 2) then |
block 2; |
… |
elif (boolean n) then |
block n; |
else |
last block; |
end |
(where the last else is optional.) For example, if you want to define a function f by
f(x) = |
|
you can enter
f(x):= { |
if (x > 8) then |
return 8; |
elif (x > 4) then |
return 4; |
elif (x > 2) then |
return 2; |
elif (x > 0) then |
return 1; |
else |
return 0; |
end; |
} |