### 10.3.1 if statements

The Xcas language has different ways of writing if…then statements (see section 4.7.2). The standard version of the if…then statement consists of the if keyword, followed by a boolean expression (see section 5.2 in parentheses, followed by a statement block which will be executed if the boolean is true.

As an example, if the variables a and b have the values 3 and 2, respectively, and you enter

if (a > b) { a := a + 5; b := a - b;}

then since a > b will evaluate to true, the variable a will be reset to 8 and b will be reset to the value 6.

An if statement can include a block of statements to execute when the boolean is false by putting it at the end following the else keyword. For example, if the variable val has a real value, then the statement

if (val > 0) {abs := val;} else {abs := -1*val; }

will set abs to the same value as val if val is positive and it will set abs to negative the value of val otherwise.

An alternate way to write an if statement is to enclose the code block in then and end instead of braces; if the variable a is equal to 3, then

if (a > 1) then a := a + 5; end

will reset a to 8. An else block can be included by putting the else statements after else and before the end. For example, with a having the value 8 as above,

if (a > 10) then a := a + 10; else a := a - 5; end

will reset a to the value 3. This can also be written:

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

Several if statements can be nested; for example, the statement

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; the above statement can be written

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 (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) =

⎧
⎪
⎪
⎨
⎪
⎪
⎩

8 | if x > 8
4 | if 4 < x ≤ 8
2 | if 2 < x ≤ 4
1 | if 0 < x ≤ 2
0 | if x ≤ 0

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;
      }