Skip to content

Information Technology · Ch 2 — Introduction to Programming

Control Structures — Decision Making

4

Control Structures — Decision Making

By default a program runs its statements sequentially, top to bottom. But real problems need the program to choose between actions depending on conditions. Decision-making (selection) statements let a program run different code for different situations.

The if statement

Runs a block only when a condition is true:

if (marks >= 35) {
    System.out.println("Pass");
}

The if...else statement

Chooses between two blocks:

if (marks >= 35) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

The if...else if ladder

Tests several conditions in turn and runs the first one that is true:

if (marks >= 75) {
    System.out.println("Distinction");
} else if (marks >= 60) {
    System.out.println("First Division");
} else if (marks >= 35) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

The conditions are checked from top to bottom; as soon as one is true its block runs and the rest are skipped, so order matters — the strictest condition must come first.

Nested if

An if may be placed inside another if to test a second condition only when the first is already true:

if (age >= 18) {
    if (hasVoterId) {
        System.out.println("Can vote");
    }
}

The switch statement

When one variable is compared against several fixed values, a switch is clearer than a long ladder:

switch (day) {
    case 1: System.out.println("Monday");   break;
    case 2: System.out.println("Tuesday");  break; …
Definition 1Selection / decision statement

A control structure (if, if-else, switch) that chooses which block of code to run base …

Definition 2Condition

A boolean expression evaluated by a decision statement to decide the path the …

Definition 3if-else-if ladder

A chain of conditions tested top to bottom; the first true condition's block runs and the …

Definition 4switch statement

A multi-way branch that compares one variable against several case values; break ends a case and `defaul …