Lesson 6 · 6 of 20
if, else and switch · C++
Make decisions in C++ with if, else if and else, choose between fixed cases with switch and break, and use the ternary operator ?:.

`if` runs a block only when the condition in brackets is true. `else if` tries another condition and `else` catches every other case. A basket of 42.5 does not reach 50 but does reach 30, so shipping is 2.99.
Conditions are checked in order and the first true one wins: with 78 points, score >= 90 fails and score >= 75 holds, so grade becomes 'B' and the rest are not even looked at. When a block has a single statement you can leave out the braces, as here.
grade starts as 'F': that is the value left if no condition holds, and it also avoids using a variable that has no value.
`switch` compares an integer or a char with several fixed `case` labels. `break` ends each case; without it, execution would fall through into the next one. `default` runs when no case matches.
The ternary operator condition ? if_true : if_false picks one of two values in a single expression: with stock at 0, it prints Sold out.
Code · main.cpp
#include <iostream>int main() { // Shipping cost in an online shop. double basket = 42.5; if (basket >= 50) { std::cout << "Free shipping\n"; } else if (basket >= 30) { std::cout << "Basket " << basket << ": shipping 2.99\n"; } else { std::cout << "Basket " << basket << ": shipping 5.99\n"; } // The first true condition wins; the rest are skipped. int score = 78; char grade = 'F'; if (score >= 90) grade = 'A'; else if (score >= 75) grade = 'B'; else if (score >= 50) grade = 'C'; std::cout << "Score " << score << " -> grade " << grade << '\n'; // switch compares one value with fixed cases; break ends each case. switch (grade) { case 'A': std::cout << "Excellent!\n"; break; case 'B': std::cout << "Very good\n"; break; case 'C': std::cout << "Passed\n"; break; default: std::cout << "Try again\n"; } // The ternary operator: condition ? if_true : if_false. int stock = 0; std::cout << (stock > 0 ? "In stock" : "Sold out") << '\n'; return 0;}Output · c++ -std=c++17 main.cpp -o main && ./main
Basket 42.5: shipping 2.99 Score 78 -> grade B Very good Sold out
Key points
if,else ifandelse: the first true condition wins.- The condition always goes in brackets.
switchcompares one value with fixedcaselabels.- Each
caseends withbreak;defaulthandles the rest. c ? a : bpicks one of two values.
Exercise
Add a switch on int day = 6; that prints "weekend" for 6 and 7 (two case labels in a row, with no break between them) and "working day" for any other day.