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 temp is greater than 25, print It's hot.

  • Add a second if: when temp is less than 10, print Wear 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 age is 18 or more, print You can vote.

  • Add an else that prints Not 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 score is 90 or more, print A.

  • Add an else if for 70 or more that prints B.

  • Finish with an else that prints C.

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 age is at least 18 and hasTicket is true, print Come in.

  • If day is 6 or day is 7, print Weekend.

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 switch on day: case 1 prints Monday, case 2 prints Tuesday, case 3 prints Wednesday. End each case with break.

  • Add a default that prints Some 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 n is divisible by both 3 and 5, print FizzBuzz.

  • Add else if branches for Fizz and Buzz, and an else that prints n.

More in C++ Basics

Previous: Operators · Next: Loops