Skip to content

Conditions: if / else / switch

Programming C++ Difficulty 1/5

Beginning of the lesson

Conditions: if / else / switch

Teach your program to make decisions

Big Idea: A program does not have to run the same way every time. With conditions it can look at a value and choose what to do next: run this block, or that one. This is how a program becomes smart.
By the end you will be able to:
  • use if to run code only when something is true,
  • use if / else to pick between two paths,
  • chain else if to test several conditions in order,
  • use switch to choose cleanly among many fixed values.

1. The idea: a fork in the road

Imagine walking and reaching a fork in the road. You ask a yes/no question — "Is it raining?" — and pick a path based on the answer. Your program does the same. It checks a condition (a question that is either true or false) and runs different code for each answer.

In C++ we ask these questions with comparison operators. Each one gives back true or false:

OperatorMeansExample (true when)
==is equal tox == 5 (x is 5)
!=is not equal tox != 5 (x is not 5)
>greater thanx > 5
<less thanx < 5
>=greater than or equalx >= 5
<=less than or equalx <= 5

Careful: == asks "are these equal?" while a single = assigns a value. They are not the same!

2. The if statement

An if runs a block of code only when its condition is true. If the condition is false, the block is skipped.

#include <iostream>
using namespace std;

int main() {
    int age = 20;

    if (age >= 18) {
        cout << "You are an adult." << endl;
    }

    return 0;
}

Output: You are an adult.

Because age is 20 and 20 >= 18 is true, the message prints. If age were 12, the condition would be false and nothing would print. The { } braces hold everything the if controls.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers