Conditional statements

### 25.3.1 Conditional statements

The Xcas language has different ways of writing “if…then” statements (see Section 5.1.3). The standard version of such a statement consists of the if keyword, followed by a boolean expression (see Section 5.1) in parentheses, followed by a statement block (see Section 25.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.

if (boolean) true-block ⟨else false-block⟩

Recall that 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 |  |  |  |  |  |  |  |  |  |

since a>b evaluates to true, and so the variable a resets to 8 and b resets to the value 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 |  |  |  |  |  |  |  |  |  |

since a>b evaluates to false, and so the variable a resets to -2 and b resets to the value 0.

##### The “if…then…else…end” structure.

An alternate way to write an if statement is to enclose the code block in then and end instead of braces:

if (boolean) then true-block ⟨else false-block⟩ end

- In this case, it is usually not necessary to enclose the boolean in parentheses.
- Instead of the keyword end, you can also use fi.

#### 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 |  |  |  |  |  |  |  |  |  |

This input can also be written as:

si a>10 alors a:=a+10; sinon a:=a-5; fsi

##### Nesting conditional statements.

Several if statements can be nested. For example:

if a>1 then a:=1; else if a<0 then a:=0; else a:=0.5; end; end

A simpler way is to replace the else if by elif and combine the ends:

if a>1 then a:=1; elif a<0 then a:=0; else a:=0.5; end

In general, such a combination can be written

if (boolean1) then
block1;
elif (boolean2) then
block2;
…
elif (booleanN) then
blockN;
else
last block;
end

where the last else is optional. For example, to define a function f by

f(x)= |
⎧ ⎪ ⎪ ⎨ ⎪ ⎪ ⎩ |
8 | if x > 8
4 | if 4 < x ≤ 8
2 | if 2 < x ≤ 4
1 | if 0 < x ≤ 2
0 | if x ≤ 0

you may 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; fi; }