---
title: "If, Else and Switch Explained with Pseudocode: Programming Fundamentals (7)"
date: "2026-09-27"
description: "Learn If, Else, ElseIf, Switch, nested and compound conditions with runnable pseudocode, using examples like even numbers and leap years."
tags: ["Programming Fundamentals", "Tutorials"]
url: "https://rolandoandrade.me/blog/programming-fundamentals-conditionals/"
author: "Rolando Andrade"
---

# If, Else and Switch Explained with Pseudocode: Programming Fundamentals (7)

> Learn If, Else, ElseIf, Switch, nested and compound conditions with runnable pseudocode, using examples like even numbers and leap years.

A conditional is an instruction that runs a group of lines only when a condition is true. With conditionals, a program stops treating every input the same way and starts making decisions. In this lesson you write programs that choose between two paths, between many paths, and between paths that depend on more than one fact at once.

In this lesson you will:

- Write simple and double conditionals with `If`, `Then`, `Else` and `EndIf`.
- Chain many options with nested conditions and `ElseIf`.
- Pick one case out of many with `Switch`.
- Combine conditions with `And`, `Or` and `Not`.
- Use `Mod` to test if a number divides another one.

It takes about 40 minutes. Every example runs in the page.

## Why programs need decisions

In the [last lesson](/blog/programming-fundamentals-sequential-structures/) you built a program that converts seconds to a clock, like `1:2:5`. It could not write `01:02:05`, because that needs a decision: write a `0` only when the number is less than 10. A sequential program runs every line, every time. It cannot skip one.

Conditionals are also called selective structures or decision structures. They evaluate a condition, which is an expression that is either true or false, and choose what to run next. You learned to write these expressions in [operators and expressions](/blog/programming-fundamentals-operators-and-expressions/): `n > 0`, `grade >= 10`, `unit = "km"`.

Most bugs that matter live in these decisions. A condition with `>` where it needed `>=` charges the wrong price, or lets in the wrong user. When an AI agent writes the code, you are the one who checks that every branch does what the business needs, including the edge cases nobody mentioned. You cannot check a branch you cannot read.

## Simple conditionals

A simple conditional runs its lines when the condition is true, and does nothing when it is false. It starts with `If`, the condition and `Then`. It ends with `EndIf`.

The lines between `Then` and `EndIf` are the body. Indent them, so the reader sees which lines belong to the `If`. After `EndIf`, the program continues in sequence, whatever the condition was.

Here is a program that says if a number is even. A number is even when it divides by 2 with no remainder, so `n Mod 2 = 0`. In [Operators and expressions](/blog/programming-fundamentals-operators-and-expressions/#practice-exercises) this test only printed `True` or `False`. Now it decides which lines run.

**Simple If: is it even?** (StepCode)

```stepcode
Program EvenNumber
    Define n As Integer;
    Write "Enter a number:";
    Read n;
    If n Mod 2 = 0 Then
        Write n, " is even";
    EndIf
    Write "Done";
EndProgram
```

Run it twice. With `8`, the condition is true:

```
Enter a number:
8 is even
Done
```

With `7`, the condition is false, so the program skips the body and writes only `Done`:

```
Enter a number:
Done
```

## Double conditionals

Most of the time you want to do one thing when the condition is true and another thing when it is false. Add `Else` between the two groups of lines. The first group runs when the condition is true, and the group after `Else` runs when it is false.

Exactly one of the two groups runs. Never both, never neither.

*Figure: Pick a value for n and switch Else on or off. Only one path lights up each time. Without Else, the false path skips the body and the program writes nothing.*

**If and Else: even or odd** (StepCode)

```stepcode
Program EvenOrOdd
    Define n As Integer;
    Write "Enter a number:";
    Read n;
    If n Mod 2 = 0 Then
        Write n, " is even";
    Else
        Write n, " is odd";
    EndIf
EndProgram
```

With `7` you see:

```
Enter a number:
7 is odd
```

In Python, the same decision looks like this. Python uses indentation instead of `EndIf`:

```python
n = int(input("Enter a number: "))
if n % 2 == 0:
    print(n, "is even")
else:
    print(n, "is odd")
```

## Many options with ElseIf

Some problems have more than two answers. Is a number positive, negative or zero? You can put an `If` inside the `Else` of another `If`. This is a nested condition. It works, but each level pushes the code further to the right.

`ElseIf` writes the same logic as one flat chain. The program checks each condition from top to bottom and runs the first one that is true. If none is true, it runs the `Else`.

**ElseIf: positive, negative or zero** (StepCode)

```stepcode
Program Sign
    Define n As Real;
    Write "Enter the number to check:";
    Read n;
    If n > 0 Then
        Write "The number is positive";
    ElseIf n < 0 Then
        Write "The number is negative";
    Else
        Write "The number is zero";
    EndIf
EndProgram
```

With `15` you see:

```
Enter the number to check:
The number is positive
```

Try `-3` and `0` too. Each input runs exactly one branch.

## Compound conditions

A compound condition joins two or more conditions with logical operators:

- `A And B` is true only when both are true.
- `A Or B` is true when at least one is true.
- `Not A` is true when `A` is false.

*Figure: Flip A and B. And needs both to be true, Or needs only one, and Not turns the value around. The lit row of the table is the case you picked.*

A classic example from the course is the leap year. A year is a leap year when it is divisible by 4 but not by 100, unless it is also divisible by 400. "Divisible by" means the remainder is zero, so you test it with `Mod`.

**Compound condition: leap year** (StepCode)

```stepcode
Program LeapYear
    Define year As Integer;
    Write "Enter a year:";
    Read year;
    If (year Mod 4 = 0 And year Mod 100 <> 0) Or year Mod 400 = 0 Then
        Write year, " is a leap year";
    Else
        Write year, " is not a leap year";
    EndIf
EndProgram
```

With `1900` you see:

```
Enter a year:
1900 is not a leap year
```

1900 divides by 4, but it also divides by 100 and not by 400, so it is not a leap year. Use parentheses when you mix `And` and `Or`. They make the order clear to the computer and to the next person who reads the code.

The same rule can also be a chain of questions. Ask the most specific question first.

*Figure: Pick a year. Each question runs only when the one above it said no, and the chain stops at the first yes. That is exactly how ElseIf works. Try 1900: it divides by 4, but the chain never gets that far.*

**The same rule as an ElseIf chain** (StepCode)

```stepcode
Program LeapYearChain
    Define year As Integer;
    Write "Enter a year:";
    Read year;
    If year Mod 400 = 0 Then
        Write year, " is a leap year";
    ElseIf year Mod 100 = 0 Then
        Write year, " is not a leap year";
    ElseIf year Mod 4 = 0 Then
        Write year, " is a leap year";
    Else
        Write year, " is not a leap year";
    EndIf
EndProgram
```

With `2000` you see:

```
Enter a year:
2000 is a leap year
```

Both programs give the same answer for every year. The first is shorter. The second is easier to read one rule at a time. Pick the one your reader will understand faster.

## Switch for one value

When every option compares the same variable with a fixed value, `Switch` is clearer than a long `ElseIf` chain. You write the variable once, then one case per value. A case can list several values separated by commas. `Otherwise` runs when no case matches. The whole block starts with `Switch variable Do` and ends with `EndSwitch`, and each case is a value followed by a colon.

Here is the calculator from class. The user picks the operation with one character.

**Switch: a calculator** (StepCode)

```stepcode
Program Calculator
    Define a, b As Real;
    Define operation As Char;
    Write "First number:";
    Read a;
    Write "Operation (+, -, *, /):";
    Read operation;
    Write "Second number:";
    Read b;
    Switch operation Do
        '+':
            Write a, " + ", b, " = ", a + b;
        '-':
            Write a, " - ", b, " = ", a - b;
        '*', 'x':
            Write a, " * ", b, " = ", a * b;
        '/':
            Write a, " / ", b, " = ", a / b;
        Otherwise:
            Write "I do not know the operation ", operation;
    EndSwitch
EndProgram
```

With `12`, `*` and `4` you see:

```
First number:
Operation (+, -, *, /):
Second number:
12 * 4 = 48
```

Both `*` and `x` multiply, because that case lists two values. Type `%` and the program falls into `Otherwise`. `Switch` only compares for equality. For ranges like "between 18.5 and 25", use `If` and `ElseIf`. In [Loops](/blog/programming-fundamentals-loops/#the-repeat-loop) this calculator goes inside a loop, so the user can do many operations in a row.

## Build a grade report

Now put it all together. This program comes from the course practice guide. It reads three exam grades, calculates the final grade and writes a message. Grades in Venezuela go from 0 to 20, and 10 is the minimum to pass.

### 1. Decide pass or fail

Start from the [rounded average](/blog/programming-fundamentals-sequential-structures/#rounded-average) you wrote at the end of the last lesson. Add one `If` with an `Else`.

**Part 1: pass or fail** (StepCode)

```stepcode
Program Grades
    Define exam1, exam2, exam3, average As Real;
    Write "Grade of exam 1:";
    Read exam1;
    Write "Grade of exam 2:";
    Read exam2;
    Write "Grade of exam 3:";
    Read exam3;
    average <- Round((exam1 + exam2 + exam3) / 3);
    If average >= 10 Then
        Write "Average ", average, ": passed";
    Else
        Write "Average ", average, ": failed";
    EndIf
EndProgram
```

Press Run and type `8`, `9` and `11`.

You should see:

```
Grade of exam 1:
Grade of exam 2:
Grade of exam 3:
Average 9: failed
```

### 2. Add a scale with nested conditions

The guide asks for a weighted average. The exams weigh 30%, 35% and 35%, so you multiply each grade by its weight. Then it asks for four messages instead of two: 18 or more is "passed with excellence", 14 or more is "passed", 10 or more is a sufficient grade, and less than 10 is "failed". Each `Else` holds the next question.

**Part 2: nested conditions** (StepCode)

```stepcode
Program Grades
    Define name, result As String;
    Define exam1, exam2, exam3, average As Real;
    Write "Name:";
    Read name;
    Write "Exam I (30%):";
    Read exam1;
    Write "Exam II (35%):";
    Read exam2;
    Write "Exam III (35%):";
    Read exam3;
    average <- Round(exam1 * 0.3 + exam2 * 0.35 + exam3 * 0.35);
    If average >= 18 Then
        result <- "passed with excellence";
    Else
        If average >= 14 Then
            result <- "passed";
        Else
            If average >= 10 Then
                result <- "passed with a sufficient grade";
            Else
                result <- "failed";
            EndIf
        EndIf
    EndIf
    Write name, " ", result, " (", average, ")";
EndProgram
```

Press Run and type `Juan Perez`, `16`, `18` and `20`.

You should see:

```
Name:
Exam I (30%):
Exam II (35%):
Exam III (35%):
Juan Perez passed with excellence (18)
```

### 3. Flatten it with ElseIf

Three `EndIf` in a row are hard to follow. Replace the nesting with an `ElseIf` chain. The logic stays the same, and the output too.

**Part 3: the same scale with ElseIf** (StepCode)

```stepcode
Program Grades
    Define name, result As String;
    Define exam1, exam2, exam3, average As Real;
    Write "Name:";
    Read name;
    Write "Exam I (30%):";
    Read exam1;
    Write "Exam II (35%):";
    Read exam2;
    Write "Exam III (35%):";
    Read exam3;
    average <- Round(exam1 * 0.3 + exam2 * 0.35 + exam3 * 0.35);
    If average >= 18 Then
        result <- "passed with excellence";
    ElseIf average >= 14 Then
        result <- "passed";
    ElseIf average >= 10 Then
        result <- "passed with a sufficient grade";
    Else
        result <- "failed";
    EndIf
    Write name, " ", result, " (", average, ")";
EndProgram
```

Press Run and type `Ana`, `12`, `10` and `9`.

You should see:

```
Name:
Exam I (30%):
Exam II (35%):
Exam III (35%):
Ana passed with a sufficient grade (10)
```

*Figure: Move the average and watch the chain check from the top. It stops at the first true condition. Then press Wrong order and try 19: the first check, 19 >= 10, is already true, so 19 gets the wrong message.*

### 4. Reject grades out of range

A grade of 25 makes no sense on a scale from 0 to 20. Check the input before you use it. A grade is wrong when it is less than 0 or greater than 20, and the input is wrong when any grade is wrong. That is a compound condition with `Or`.

**Part 4: validate the input** (StepCode)

```stepcode
Program Grades
    Define name, result As String;
    Define exam1, exam2, exam3, average As Real;
    Write "Name:";
    Read name;
    Write "Exam I (30%):";
    Read exam1;
    Write "Exam II (35%):";
    Read exam2;
    Write "Exam III (35%):";
    Read exam3;
    If exam1 < 0 Or exam1 > 20 Or exam2 < 0 Or exam2 > 20 Or exam3 < 0 Or exam3 > 20 Then
        Write "Every grade must be between 0 and 20";
    Else
        average <- Round(exam1 * 0.3 + exam2 * 0.35 + exam3 * 0.35);
        If average >= 18 Then
            result <- "passed with excellence";
        ElseIf average >= 14 Then
            result <- "passed";
        ElseIf average >= 10 Then
            result <- "passed with a sufficient grade";
        Else
            result <- "failed";
        EndIf
        Write name, " ", result, " (", average, ")";
    EndIf
EndProgram
```

Press Run and type `Ana`, `16`, `25` and `20`.

You should see:

```
Name:
Exam I (30%):
Exam II (35%):
Exam III (35%):
Every grade must be between 0 and 20
```

## Common mistakes

If you see `A condition has to be Boolean, and this one is Integer: compare explicitly, for example "… <> 0".`, it means the condition is a number, not a true or false value. You probably wrote `If n Mod 2 Then`. Compare the result: `If n Mod 2 = 0 Then`.

If you see `An expression is missing here: I found "<".`, it means a comparison lost its left side. `n > 0 And < 10` reads well in English, but each comparison needs both sides: `n > 0 And n < 10`.

If you see `"EndIf" is missing: the "If" on line 4 is never closed.`, add the `EndIf`. Every `If` needs exactly one, no matter how many `ElseIf` it has.

If a grade of 19 says "sufficient", your `ElseIf` chain is in the wrong order. The chain stops at the first true condition, and 19 is also `>= 10`. Put the most demanding condition first. The computer gives no error here. The code runs and the answer is wrong. This is a [logic error](/blog/programming-fundamentals-design-and-development-of-algorithms/#logic-errors-give-wrong-answers), and only a person who reads the conditions can find it.

## If or Switch

Both choose between paths. Use the one that matches the shape of the question.

| The question is | Use |
| --- | --- |
| Is something true? | `If` |
| This or that? | `If` with `Else` |
| Which range is the value in? | `If` with `ElseIf` |
| Do several facts hold at once? | `If` with `And`, `Or`, `Not` |
| Which exact value does one variable have? | `Switch` |

A conditional chooses once. If you need to do something again and again, like asking until the input is valid, that is a loop, the topic of the [next lesson](/blog/programming-fundamentals-loops/).

## Practice exercises

Try each one in an empty editor first. The numbers in your output must match. Your messages can differ.

### Finish the clock

Go back to the [seconds converter](/blog/programming-fundamentals-sequential-structures/#4-write-the-final-output) from the last lesson. Write each part with two digits. Hint: `WriteNoNewline` writes without moving to a new line, so you can write a `0` first only when the number is less than 10.

Input `3725` gives:

```
Enter the number of seconds:
01:02:05
```

**Solution: finish the clock** (StepCode)

```stepcode
Program Clock
    Define totalSeconds, hours, minutes, seconds, rest As Integer;
    Write "Enter the number of seconds:";
    Read totalSeconds;
    hours <- totalSeconds Div 3600;
    rest <- totalSeconds Mod 3600;
    minutes <- rest Div 60;
    seconds <- rest Mod 60;
    If hours < 10 Then
        WriteNoNewline "0";
    EndIf
    WriteNoNewline hours, ":";
    If minutes < 10 Then
        WriteNoNewline "0";
    EndIf
    WriteNoNewline minutes, ":";
    If seconds < 10 Then
        WriteNoNewline "0";
    EndIf
    Write seconds;
EndProgram
```

### Body mass index

Ask for a name, the height in meters and the weight in kilograms. The body mass index (BMI) is the weight divided by the height squared. Less than 18.5 is underweight. From 18.5 to less than 25 is a normal weight. From 25 to less than 30 is overweight. 30 or more is obesity. Show the BMI with one decimal.

Inputs `Juan Perez`, `1.8` and `78` give:

```
Name:
Height (meters):
Weight (kilograms):
Juan Perez has a normal weight and a BMI of 24.1
```

**Solution: body mass index** (StepCode)

```stepcode
Program BodyMassIndex
    Define name, category As String;
    Define height, weight, bmi As Real;
    Write "Name:";
    Read name;
    Write "Height (meters):";
    Read height;
    Write "Weight (kilograms):";
    Read weight;
    bmi <- weight / (height * height);
    If bmi < 18.5 Then
        category <- "underweight";
    ElseIf bmi >= 18.5 And bmi < 25 Then
        category <- "a normal weight";
    ElseIf bmi >= 25 And bmi < 30 Then
        category <- "overweight";
    Else
        category <- "obesity";
    EndIf
    Write name, " has ", category, " and a BMI of ", Round(bmi * 10) / 10;
EndProgram
```

### Even and multiples

Ask for a number. Write every label that applies: "Even", "Multiple of 3" and "Multiple of 10". A number can have none, one or all three. This is why you need three separate `If`, not one `ElseIf` chain.

Input `30` gives:

```
Enter a number:
n = 30, Even, Multiple of 3, Multiple of 10
```

**Solution: even and multiples** (StepCode)

```stepcode
Program Multiples
    Define n As Integer;
    Write "Enter a number:";
    Read n;
    WriteNoNewline "n = ", n;
    If n Mod 2 = 0 Then
        WriteNoNewline ", Even";
    EndIf
    If n Mod 3 = 0 Then
        WriteNoNewline ", Multiple of 3";
    EndIf
    If n Mod 10 = 0 Then
        WriteNoNewline ", Multiple of 10";
    EndIf
    Write "";
EndProgram
```

These editors run on [StepCode](/projects/stepcode/), the pseudocode language I built for my students at UCAB.

## What you learned

- `If` runs its body only when the condition is true. `Else` gives the other path, and exactly one path runs.
- `ElseIf` checks conditions from top to bottom and stops at the first true one, so order matters.
- `Switch` picks a case by the exact value of one variable. `Otherwise` catches the rest.
- `And`, `Or` and `Not` join conditions. Use parentheses when you mix them.
- `n Mod d = 0` tests if `n` divides by `d`. It powers even numbers, multiples and leap years.

## Next steps

Your programs can now decide, but each line still runs at most once. In the next lesson, [loops](/blog/programming-fundamentals-loops/), you repeat instructions with `While`, `Repeat` and `For`, and build programs like a factorial, a multiplication table and a prime number checker.
