Conditionals
Programming Languages · C++ Basics · 12 min
Make your program choose what to do with if, else, && || ! and switch.
Making a choice with if
An if runs code only when a condition is true. The condition goes in round brackets, the code to run goes in curly braces:
if (lives > 0) {
std::cout << "Keep playing\n";
}
If
tempis greater than 25, printIt's hot.Add a second
if: whentempis less than 10, printWear a coat. Nothing new should print, since it's 30.
Otherwise: else
else is the plan B. It runs when the if condition is false. Exactly one of the two blocks runs:
if (coins >= 10) {
std::cout << "Buy it\n";
} else {
std::cout << "Too expensive\n";
}
If
ageis 18 or more, printYou can vote.Add an
elsethat printsNot yet.
More choices: else if
Need more than two options? Chain them with else if. C++ checks each condition from the top and runs the first one that's true:
if (speed > 100) {
std::cout << "Too fast\n";
} else if (speed > 50) {
std::cout << "Nice pace\n";
} else {
std::cout << "Slow\n";
}
If
scoreis 90 or more, printA.Add an
else iffor 70 or more that printsB.Finish with an
elsethat printsC.
And, or, not
Combine conditions with:
&&and: both sides must be true||or: at least one side is true!not: flips true to false
if (hungry && hasMoney) {
std::cout << "Get pizza\n";
}
If
ageis at least 18 andhasTicketis true, printCome in.If
dayis 6 ordayis 7, printWeekend.
Many exact values: switch
When you compare one variable against many exact values, switch is tidier than a long else-if chain. Each case is one value. break ends that case (forget it and C++ runs straight into the next one!). default catches everything else.
switch (level) {
case 1:
std::cout << "Easy\n";
break;
default:
std::cout << "Hard\n";
}
Write a
switchonday: case 1 printsMonday, case 2 printsTuesday, case 3 printsWednesday. End each case withbreak.Add a
defaultthat printsSome other day.
Put it together: FizzBuzz
A classic! For a number n:
- divisible by 3 and 5: print
FizzBuzz - only by 3: print
Fizz - only by 5: print
Buzz - otherwise: print the number
"Divisible by 3" means no leftover: n % 3 == 0. Check the FizzBuzz case first, or Fizz would win.
If
nis divisible by both 3 and 5, printFizzBuzz.Add
else ifbranches forFizzandBuzz, and anelsethat printsn.