4.x — Chapter 4 summary and quiz

📘 Chapter 4⏱ about 3 min read✍️ Beginner friendly
Read one box at a time. No rush.

Quick review#

  • if (condition) { } runs code only when the condition is true.
  • else runs when it is false. else if adds more choices.
  • Only the first true branch runs.
  • switch picks from exact values. End each case with break;.
  • Always use { } and == (not =). Never put ; right after if (...).
Quick check

Pick an answer. You find out right away if it is right.

Quick check #1

In an if / else if chain, how many branches can run?

Quick check #2

What does break; do inside a switch?

Quick check #3

What's wrong with if (score = 10)?

Quiz time
Question #1

What prints when x is 7?

C++
if (x > 10){    std::cout << "big";}else if (x > 5){    std::cout << "medium";}else if (x > 0){    std::cout << "small";}

medium. 7 is not > 10, but it is > 5. It is also > 0, but C++ stops at the first true branch.

Question #2

Find the bug:

C++
if (password == "secret");{    std::cout << "Access granted\n";}

There is a semicolon ; right after the if (...). It ends the if, so "Access granted" always prints. Remove the ;.

Question #3

Write a program that asks for a number and prints whether it is positive, negative, or zero.

C++▶ Run
#include <iostream> int main(){    std::cout << "Enter a number: ";    int n {};    std::cin >> n;     if (n > 0)    {        std::cout << "positive\n";    }    else if (n < 0)    {        std::cout << "negative\n";    }    else    {        std::cout << "zero\n";    }    return 0;}
Question #4

Write a tiny calculator: ask for two numbers and an operator (+, -, * or /), then print the answer. Use a switch. Don't forget about dividing by zero!

C++▶ Run
#include <iostream> int main(){    double a {};    double b {};    char op {};     std::cout << "Enter: number operator number (e.g. 4 * 5): ";    std::cin >> a >> op >> b;     switch (op)    {    case '+':        std::cout << a + b << '\n';        break;    case '-':        std::cout << a - b << '\n';        break;    case '*':        std::cout << a * b << '\n';        break;    case '/':        if (b == 0)        {            std::cout << "Can't divide by zero!\n";        }        else        {            std::cout << a / b << '\n';        }        break;    default:        std::cout << "Unknown operator\n";        break;    }    return 0;}
Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.