Command Palette

Search for a command to run...

MTH 4300

Lecture 3

if-else statements

Hopefully, we still remember conditional statements. But as a quick primer, conditional statements allow us to gate the execution of code. Here's a quick example from Python-land to jog our memories.

Previously in Python
some_number_from_user = int(input("Enter a number here: "))

if some_number_from_user % 2 == 0:
    print(f"{some_number_from_user} is an even number")
else:
    print(f"{some_number_from_user} is an odd number")

The idea doesn't really change in C++. For the equivalent code as above, we'll have the following implementation

Now in C++
#include <iostream>

int main() {
    int some_number_from_user;
    std::cout << "Enter a number here: ";
    std::cin >> some_number_from_user;

    if (some_number_from_user % 2 == 0) {
        std::cout << some_number_from_user << " is an even number" << std::endl;
    } else {
        std::cout << some_number_from_user << " is an odd number" << std::endl;
    }

    return 0;
}

else-if statements

We can have more than just an if and an else statement. We can chain intermediate conditions using an else-if statement. This is equivalent to the elif statement in Python.

In an else-if chain, execution stops at the first matching condition; remaining clauses are skipped entirely.

This is different from writing separate if statements: if you replaced each else if with a standalone if, a number like 15 would match multiple conditions and print both Fizz and Buzz instead of FizzBuzz.

FizzBuzz
#include <iostream>

int main() {
    int num;
    std::cin >> num;

    if (num % 3 == 0 && num % 5 == 0) {
        std::cout << "FizzBuzz" << std::endl;
    } else if (num % 3 == 0) {
        std::cout << "Fizz" << std::endl;
    } else if (num % 5 == 0) {
        std::cout << "Buzz" << std::endl;
    }

    return 0;
}

Nested conditional statements

Nested conditionals are if statements placed inside the body of another if or else block. Python has the exact same concept — the only difference in C++ is that we use braces instead of indentation to define the blocks.

A good use case is when an inner condition only makes sense if an outer condition is already true. For example, we only care about which letter grade a student earned if they're passing in the first place:

Grade Classifier
#include <iostream>

int main() {
    int score;
    std::cin >> score;

    if (score >= 60) {
        if (score >= 90) {
            std::cout << "A" << std::endl;
        } else if (score >= 80) {
            std::cout << "B" << std::endl;
        } else if (score >= 70) {
            std::cout << "C" << std::endl;
        } else {
            std::cout << "D" << std::endl;
        }
    } else {
        std::cout << "F" << std::endl;
    }

    return 0;
}

Nesting is appropriate when the inner condition only makes sense if the outer condition is true — as above, there's no point classifying the letter grade if the student is already failing. If the conditions are independent of each other, prefer else-if or separate if statements instead.

Deep nesting (3+ levels) quickly becomes hard to read and reason about. If you find yourself nesting more than two levels deep, it's usually a sign to restructure using else-if chains or to extract the inner logic into a function (we'll cover functions in a later lecture).

switch statements

A switch statement is a cleaner alternative to a long else-if chain when you need to match a single variable against a set of discrete constant values. Python didn't have an equivalent until match/case in 3.10, so this may look new.

Day of Week
#include <iostream>

int main() {
    int day;
    std::cin >> day;

    switch (day) {
        case 1:
            std::cout << "Monday\n";
            break;
        case 2:
            std::cout << "Tuesday\n";
            break;
        case 3:
            std::cout << "Wednesday\n";
            break;
        case 4:
            std::cout << "Thursday\n";
            break;
        case 5:
            std::cout << "Friday\n";
            break;
        case 6:
            std::cout << "Saturday\n";
            break;
        case 7:
            std::cout << "Sunday\n";
            break;
        default:
            std::cout << "Invalid day\n";
            break;
    }

    return 0;
}

The default case acts like the final else — it runs if none of the case values matched.

Don't forget break

Without a break at the end of a case, execution falls through into the next case — even if its condition didn't match. For example:

switch (day) {
    case 6:
        std::cout << "Saturday\n";
        // missing break!
    case 7:
        std::cout << "Sunday\n";
        break;
}

If day is 6, this prints both Saturday and Sunday. Fallthrough is occasionally used intentionally, but it's almost always a bug.

switch only works with integral types

You can only switch on int, char, enum, and other integer-like types. Switching on a std::string or a double is a compile error — use an else-if chain for those cases instead.

Loops

Loops let us repeat a block of code without writing it out multiple times. C++ has two main loop types: for and while.

for loops

Use a for loop when you know how many times you want to iterate. The loop header has three parts separated by semicolons: initialization, condition, and update.

Counting with a for loop
#include <iostream>

int main() {
    for (int i = 0; i < 5; i++) {
        std::cout << i << "\n";
    }

    return 0;
}

This prints 0 through 4. The Python equivalent is for i in range(5) — same idea, just different syntax.

while loops

Use a while loop when you don't know ahead of time how many iterations you'll need — the loop runs as long as its condition remains true.

A classic use case is input validation: keep prompting the user until they give you a valid value.

Input Validation
#include <iostream>

int main() {
    int age;
    std::cout << "Enter a positive age: ";
    std::cin >> age;

    while (age <= 0) {
        std::cout << "Invalid! Enter a positive age: ";
        std::cin >> age;
    }

    std::cout << "Your age is: " << age << "\n";

    return 0;
}
Watch out for infinite loops

If the loop condition never becomes false, your program will run forever. Always make sure something inside the loop body can eventually make the condition false — in the example above, reading a new value of age on each iteration is what gives the loop a way to exit.

Exercises

Q1.

Answer the following questions about switch statements:

  1. Give one scenario where a switch is preferable to an else-if chain. What makes it cleaner?
  2. Give one scenario where you cannot use a switch and must use else-if instead. Why?
  3. What happens if you omit break from every case in a switch? Walk through an example.

Q2.

Without running the code, determine what this program prints. Then verify by compiling and running.

#include <iostream>

int main() {
    int sum = 0;

    for (int i = 1; i <= 5; i++) {
        sum += i;
        std::cout << "i=" << i << " sum=" << sum << "\n";
    }

    return 0;
}

Q3.

Write a complete C++ program that reads integers from the user one at a time and keeps a running total. Stop reading when the user enters 0, then print the sum. Do not include 0 in the sum.

Example:

Enter a number (0 to stop): 4
Enter a number (0 to stop): 7
Enter a number (0 to stop): -2
Enter a number (0 to stop): 0
Sum: 9
#include <iostream>

int main() {
    int sum = 0;
    int num;

    // TODO: read integers in a loop until the user enters 0
    // TODO: add each non-zero number to sum

    std::cout << "Sum: " << sum << "\n";

    return 0;
}

Q4.

The program below is supposed to print the season for a given month number (1–12), but it has bugs. Identify what's wrong in each case, explain why, and write a corrected version.

#include <iostream>

int main() {
    int month;
    std::cin >> month;

    switch (month) {
        case 12:
        case 1:
        case 2:
            std::cout << "Winter\n";
        case 3:
        case 4:
        case 5:
            std::cout << "Spring\n";
            break;
        case 6:
        case 7:
        case 8:
            std::cout << "Summer\n";
            break;
        case 9:
        case 10:
        case 11:
            std::cout << "Fall\n";
            break;
    }

    return 0;
}

Practice Problems