4.x — Chapter 4 summary and quiz
Quick review#
if (condition) { }runs code only when the condition is true.elseruns when it is false.else ifadds more choices.- Only the first true branch runs.
switchpicks from exact values. End eachcasewithbreak;.- Always use
{ }and==(not=). Never put;right afterif (...).
Pick an answer. You find out right away if it is right.
In an if / else if chain, how many branches can run?
C++ checks from the top and runs only the first branch whose condition is true.
What does break; do inside a switch?
Without break, C++ "falls through" into the next case.
What's wrong with if (score = 10)?
= assigns. To compare, use ==.
What prints when x is 7?
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.
Find the bug:
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 ;.
Write a program that asks for a number and prints whether it is positive, negative, or zero.
#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;}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!
#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;}Tip: press ← / → to move between lessons, / to search.