# 6.1 The If decision

> `If` asks a question whose answer can only be `True` or `False`, and runs one path or the other depending on the answer. Never both.

Web page: https://pseudolearn.app/en/spec/control/si

> **In one sentence**
>
> `If` asks a question whose answer can only be `True` or `False`, and runs one path or the other depending on the answer. Never both.

## 6.1.1 How to write it

```pseudolearn
If «condición» Then
  «instrucciones si es verdadera»
⟦Else
  «instrucciones si es falsa»⟧
EndIf
```

> **Parts**
>
> - `If` opens the decision.
> - «condition» is any expression whose result is a `Boolean`: a comparison such as `age >= 18`, a boolean variable or a combination with `And`, `Or` and `Not`.
> - `Then` separates the question from what is done. It is always required.
> - «statements» are zero or more statements. An empty body is valid.
> - `Else` is optional. It introduces what is done when the condition is false. Without it, it is as if its body were empty.
> - `EndIf` closes the decision. After it, the program continues the same way whichever path was taken.

## 6.1.2 How it works

Without `Else`, `If` is an optional detour. If the answer is `True`, something extra is done; if it is `False`, nothing happens and the program carries on.

### Program: Do I take an umbrella?

```pseudolearn
Algorithm Paraguas
  Define llueve As Boolean <- True;
  If llueve Then
    Write "Llevo el paraguas";
  EndIf
  Write "Salgo de casa";
EndAlgorithm
```

**Output**

```text
Llevo el paraguas
Salgo de casa
```

*The program finishes normally.*

With `Else` there are two paths and **exactly one** is taken. Step through the figure to see what the engine does with this program.

### Program: Can I ride the roller coaster?

```pseudolearn
Algorithm Montana
  Define estatura As Integer <- 128;
  If estatura >= 120 Then
    Write "Puedes subir a la montaña rusa";
  Else
    Write "Todavía no: vuelve el año que viene";
  EndIf
EndAlgorithm
```

**Output**

```text
Puedes subir a la montaña rusa
```

*The program finishes normally.*

**Figure 6.1-1: Step-by-step run of Montana**

A flowchart with the start, the assignment of estatura, a diamond asking whether estatura is greater than or equal to 120, two boxes with the Write of each branch, the point where they join and the end. Each step highlights the part being run.

An `If` walked through step by step. The diamond is the question; two arrows leave it and only one is followed.

1. Step 1: `Define estatura As Integer <- 128;` runs. The variable appears in memory with the value 128.
2. Step 2: The engine reaches the `If` and **evaluates the condition only once**: `128 >= 120` gives `True`.
3. Step 3: Since the answer is `True`, it follows the `Then` branch and runs its `Write`.
4. Step 4: The `Else` branch is not run: it is not evaluated, writes nothing and does not change memory.
5. Step 5: At `EndIf` both paths join. Nothing else remains, so the program ends.

> **Analogy**
>
> An `If` is like a fork in a trail with a sign that asks a question. You can only take one path, and further on both join again at `EndIf`. The analogy stops working at one point: here you cannot go back and try the other path. Repeating needs a loop.

## 6.1.3 More than two paths

PseudoLearn has no special word for "else if". When there are more than two cases, an `If` goes inside the `Else` of another, and each has its own `EndIf`. That way every decision always has exactly two exits.

### Program: The grade traffic light

```pseudolearn
Algorithm Semaforo
  Define nota As Integer <- 7;
  If nota >= 9 Then
    Write "Excelente";
  Else
    If nota >= 6 Then
      Write "Aprobado";
    Else
      Write "A repasar";
    EndIf
  EndIf
EndAlgorithm
```

**Output**

```text
Aprobado
```

*The program finishes normally.*

The questions are asked in order and the first one that answers `True` wins. That is why order matters: if `nota >= 6` were asked first, a 10 would also say "Aprobado". When the cases are concrete values rather than ranges, [Switch](https://pseudolearn.app/en/spec/control/segun.md) reads better.

## 6.1.4 Compound conditions

A condition can combine several questions with `And`, `Or` and `Not`. The engine evaluates them **from left to right and stops as soon as it knows the answer**. With `And`, if the left part is `False`, the right part is never looked at. That lets you protect a dangerous operation.

### Program: Divide only when possible

```pseudolearn
Algorithm Corto
  Define divisor As Integer <- 0;
  If divisor <> 0 And 10 / divisor > 1 Then
    Write "Grande";
  Else
    Write "No se puede dividir";
  EndIf
EndAlgorithm
```

**Output**

```text
No se puede dividir
```

*The program finishes normally.*

Since `divisor <> 0` is `False`, the division `10 / divisor` is never computed and the program does not stop for dividing by zero.

> **Common mistakes**
>
> The engine requires the condition to be a `Boolean`. A number does not work as a question:
>
> ### Program: A condition that is not boolean
>
> ```pseudolearn
> Algorithm ErrorNumero
>   Define edad As Integer <- 12;
>   If edad Then
>     Write "Hola";
>   EndIf
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `nonBooleanCondition` (error, 3:6): Condition must be a boolean expression
>
> *The program finishes with an error.*
>
> To fix it, write the full question: `edad > 10`.
>
> Forgetting `Then` is also detected before running:
>
> ### Program: Then is missing
>
> ```pseudolearn
> Algorithm ErrorEntonces
>   Define edad As Integer <- 12;
>   If edad > 10
>     Write "Hola";
>   EndIf
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `expectedThenKeyword` (error, 3:15): Expected then keyword
>
> *The program finishes with an error.*
>
> And an `If` without its `EndIf` leaves the decision open:
>
> ### Program: EndIf is missing
>
> ```pseudolearn
> Algorithm ErrorCierre
>   Define edad As Integer <- 12;
>   If edad > 10 Then
>     Write "Hola";
> EndAlgorithm
> ```
>
> **Diagnostics**
> - `unclosedIfStatement` (error, 5:1): Unclosed if statement
>
> *The program finishes with an error.*

> **Under the hood**
>
> The engine turns every `If` into blocks of the intermediate representation. A `branch` instruction chooses between two blocks according to a boolean value. Notice how the short circuit of `And` shows up as a jump: if `divisor <> 0` is false, it jumps straight to a block holding `false` without computing the division.
>
> **Intermediate representation**
>
> ```text
> module Corto en
> func suspendible @main() -> unit {
> b0() mass 2:
>   stmt.enter @2:3-2:33
>   %0 = const.i64 0 @2:32-2:33
>   stmt.exit @2:3-2:33
>   stmt.enter @3:3-7:8
>   %1 = const.i64 0 @3:17-3:18
>   %2 = int.cmp ne, %0, %1 @3:14-3:16
>   branch %2, b1(), b2()
> b1() mass 0:
>   %3 = const.i64 10 @3:23-3:25
>   %4 = int.to_real %3 @3:23-3:25
>   %5 = int.to_real %0 @3:28-3:35
>   %6 = real.div %4, %5 @3:26-3:27
>   %7 = const.i64 1 @3:38-3:39
>   %8 = int.to_real %7 @3:38-3:39
>   %9 = real.cmp gt, %6, %8 @3:36-3:37
>   jump b3(%9)
> b2() mass 0:
>   %10 = const.bool false
>   jump b3(%10)
> b3(%11: bool) mass 0:
>   decide.bool %11 @3:3-7:8
>   branch %11, b4(), b5()
> b4() mass 1:
>   stmt.enter @4:5-4:19
>   %12 = const.str "Grande" @4:11-4:19
>   out.write %12, newline @4:5-4:19
>   stmt.exit @4:5-4:19
>   jump b6()
> b5() mass 1:
>   stmt.enter @6:5-6:32
>   %13 = const.str "No se puede dividir" @6:11-6:32
>   out.write %13, newline @6:5-6:32
>   stmt.exit @6:5-6:32
>   jump b6()
> b6() mass 0:
>   stmt.exit @3:3-7:8
>   return @8:1-8:13
> }
> ```
>
> The trace records the decision with its branch:
>
> **Trace**
>
> | Line | Event |
> | --- | --- |
> | 2 | enters statement |
> | 3 | enters statement |
> | 3 | decision · true branch |
> | 4 | enters statement |
> | 4 | writes · Puedes subir a la montaña rusa |

> **Note**
>
> The most common confusion is believing that both branches run, or that `Else` is required. Predict the output of `semaforo` with grades 5, 6, 9 and 10 before running it. Another frequent confusion is writing `If nota >= 6 And nota < 9` when the `Else` already guarantees that `nota < 9`.

**In short**
- `If` asks something that can only be answered with `True` or `False`.
- Exactly one path runs; `Else` is optional.
- `Then` and `EndIf` are required.
- For more than two cases decisions are nested; the first true question wins.
- `And` and `Or` stop as soon as they know the answer.

**See also**
- [4.5 Logical operators](https://pseudolearn.app/en/spec/expresiones/logicos.md)
- [6.2 Multiple selection with Switch](https://pseudolearn.app/en/spec/control/segun.md)
- [3.1 Primitive types](https://pseudolearn.app/en/spec/tipos/primitivos.md)
