KTU S1

Selection — the if-else Structure

By the end you should be able to: Write pseudocode using if, if-else and nested if-else structures, and trace which branch executes for given input.

Selection chooses between alternative paths based on a condition. This is where a program stops being a fixed recipe and starts responding to its input.

The three forms

1. Simple IF — do something, or don't.

IF condition THEN
    statements
ENDIF

2. IF-ELSE — choose one of two.

IF condition THEN
    statements A
ELSE
    statements B
ENDIF

Exactly one branch runs. Never both, never neither.

3. Nested / chained IF-ELSE — choose one of many.

IF condition1 THEN
    statements A
ELSE IF condition2 THEN
    statements B
ELSE
    statements C
ENDIF

Conditions

A condition is anything that evaluates to true or false.

OperatorMeaning
= or ==equal to
≠ or <>not equal to
< > ≤ ≥comparisons
ANDboth must hold
ORat least one holds
NOTnegation

AND binds tighter than OR, so a OR b AND c means a OR (b AND c). Parenthesise when in doubt — the same advice as everywhere else.

The ordering trap

In a chained IF-ELSE, conditions are tested top to bottom and the first true one wins. Order therefore changes behaviour.

Wrong:

IF marks >= 50 THEN
    PRINT "Pass"
ELSE IF marks >= 90 THEN
    PRINT "Distinction"        ← unreachable
ENDIF

A student with 95 matches the first condition and gets "Pass". The second branch can never execute, because anything ≥ 90 is also ≥ 50.

Rule: in a chain of overlapping conditions, test the most restrictive first. For grade boundaries, that means highest first.

The dangling ELSE

IF a > 0 THEN
    IF b > 0 THEN
        PRINT "both positive"
ELSE
    PRINT "???"
ENDIF

Which IF does that ELSE belong to? Ambiguous, and different languages resolve it differently. Always use explicit ENDIF and consistent indentation so the question never arises.

Don't test what you already know

IF marks >= 50 AND marks < 100 THEN     ← redundant in a chain

Inside an ELSE branch you already know the previous condition was false. Retesting it adds clutter and opportunities for error.