W1034 Booleans

From Coder Merlin
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Introduction[edit]

A boolean is a data type in programming that can have one of two states: true or false. This is also sometimes referred to as on/off and 1/0.

Examples[edit]

Even without knowing it, you're making use of booleans whenever you write a program. Here are a few examples:

Conditionals[edit]

Whenever you use a conditional statement in programming, the condition eventually resolves into a boolean true or false. If the condition resolves to true, the consequent is executed, otherwise the alternative is. For example, consider the following conditional to determine if the number is even:

let x = 15

if (x % 2 == 0) {
    print("\(x) is even!")
} else {
    print("\(x) is not even!")
}

This will result in the alternative running because 15 is not even. The conditional, checking if the modulus of 15 and 2 is equal to zero is binary; it is either true and the number is even or false and the number is not even. Even in conditional statements with more than two branches (i.e. using else if), each statement is still eventually resolved into a true or a false. Here's an illustrative example:

let x = 15

if (x % 2 == 0) {
    print("\(x) is even!")
} else if (x % 3 == 0) {
    print("\(x) is a multiple of 3!")
} else {
    print("\(x) is not even and not a multiple of 3!")
}

This is functionally equivalent to:

let x = 15

if (x % 2 == 0) {
    print("\(x) is even!")
} else {
    if (x % 3 == 0) {
        print("\(x) is a multiple of 3!")
    } else {
        print("\(x) is not even and not a multiple of 3!")
    }
}

If there are more else if statements, they can continue to be added into the most recent alternative. In other words, another else if statement to check if the number is divisible by seven could be added as follows:

...
    if (x % 3 == 0) {
        print("\(x) is a multiple of 3!")
    } else {
        if (x % 7 == 0) {
            print("\(x) is divisible by 7")
        } else {
            print("\(x) is not even and not a multiple of 3 or 7!")
        }
    }
...

Relational Operations[edit]

Equality[edit]

The CPU lacks an instruction set to directly compare the values of two numbers. Instead, to check if two numbers are equal, one number is subtracted from the other. If both of the numbers are equal, then the difference will be equal to zero. Otherwise, the difference will be non-zero, indicating that the numbers were not equal.

For example, in order to compare 10 and 3, the difference can be calculated: 10 - 3 = 7. Since the difference is not equal to zero, the equality is false because the numbers are not equal. As another example, let's compare -150 and -150, the difference is: -150 - (-150) = 0. Since the difference is equal to zero, it can be concluded that the numbers are in fact equal.