Lecture 05: Booleans and Decisions

Jan 24, 2024  β”‚  Last updated Jan 17, 2024 by Charlotte Curtis

HTML Slides html β”‚ PDF Slides PDF

Where we left off

if (boolean_expression) {
    // code to execute if true
} else {
    // code to execute if false
}

Today’s topics

Textbook Sections 2.4, 3.1-3.2

The bool data type

Reading and printing booleans

Boolean operators

PythonC++Description
and&&Logical and
or||Logical or
not!Logical not

cout and precedence

if syntax

if (boolean_expression) {
    // code to execute if true
} else {
    // code to execute if false
}

Caution!

bg left:60% fit

Single line if statements

Nested if statements

Just like Python, you can nest if statements inside each other:

if (is_valid_account_number(account_number) {
    if (max_disk_usage > allotment) {
        // surcharge calculation
    }
}

Multiple branching with else if

Python

if x > 0:
    print("x is positive")
elif x < 0:
    print("x is negative")
else:
    print("x is zero")

C++

if (x > 0) {
    cout << "x is positive\n";
} else if (x < 0) {
    cout << "x is negative\n";
} else {
    cout << "x is zero\n";
}

Tricky mistakes

emoji if statement check-in

In the following code snippet, x has a value of 15. What is the output?

  1. Fizz
  2. Buzz
  3. FizzBuzz
  4. Nothing
  5. Error
if (x % 3 == 0)
    cout << "Fizz";
if (x % 5 == 0)
    cout << "Buzz";

emoji A trickier one

What is the output of the following code snippet? x is again 15.

  1. x is 0
  2.  x is 0
     Try again
    
  3. Try again
  4. Nothing
  5. Error
if (x == 0)
    cout << "x is 0\n";
    cout << "Try again\n";

Branching in functions

C++ does not restrict you to a single return statement in a function:

double relu(double x) {
    if (x > 0)
        return x;
    else
        return 0;
}

Tangent: Guard clauses

A “guard clause” is an if statement that returns early if inputs are invalid

bool is_valid_account_number(int account_number) {
    if (account_number < 0) {
        return false;
    }
    
    // rest of function
}

And now, loops!

while condition:
    # code to execute
while (condition) {
    // code to execute
}

Complete while loop example

int x = 1;              // Initialization
while (x <= 100) {      // Condition
    if (x % 3 == 0)
        cout << "Fizz";
    if (x % 5 == 0)
        cout << "Buzz";
    cout << "\n";
    x++;                // Update
}

for loops - a bit more different

for i in range(10):
    # code to execute
for (int i = 0; i < 10; i++) {
    // code to execute
}

FizzBuzz as a for loop

Since FizzBuzz is counting from 1 to 100, it’s a good candidate for a for loop:

for (int x = 1; x <= 100; x++) {
    if (x % 3 == 0)
        cout << "Fizz";
    if (x % 5 == 0)
        cout << "Buzz";
    cout << "\n";
}

Coming up next

Textbook sections 3.3-3.4



Previous: Lecture 04: Pass by reference
Next: Lecture 06: Loops