A girl and a robot thinking together

Let’s think it through · Start with a story

Before leaving, the girl tells the robot, “Take an umbrella if it rains.” What does the robot need to know first?

Break down the process

Follow the numbered steps, then explain them in your own words
  1. ObserveIs it raining?
  2. CheckIs the condition true?
  3. TrueTake an umbrella
  4. FalseSkip this action

if lets a program decide whether to execute a statement based on a condition.

The program evaluates the condition first, then decides whether to enter the branch. Braces group together the actions that belong to that branch.

01Why do programs need “choices”?

Many tasks should not do the same thing every time.

For example, print “Pass” only when the score is at least 60.

if (score >= 60) {
    std::cout << "Pass";
}

02How does if work?

Evaluate the condition→true?→Run the code block

If the condition is false, the program skips this block and continues with the code that follows.

03Must a condition be a comparison expression?

Not necessarily. The condition in if must be convertible to bool.

bool ready = true;

if (ready) {
    std::cout << "Start";
}

Integers can also convert to bool: 0 is false, and nonzero values are true. As a beginner, though, it is best to write conditions that are clear and direct.

04Is if “thinking”?

No. The computer is not deciding for itself what is good or bad.

It is simply following rules written by the programmer:

A person’s job

Design “what should happen, and when.”

The computer’s job

Evaluate the condition and follow the matching path exactly.

05Why do braces matter?

if (score >= 60) {
    std::cout << "Pass";
    std::cout << "Keep it up";
}

Braces group multiple statements into one code block.

06What happens with multiple if statements?

if (score >= 60) {
    std::cout << "Pass";
}

if (score == 100) {
    std::cout << "Perfect score";
}

These are two independent if statements. Each condition is checked separately, so both code blocks may run.

What you have learned

  • if uses a condition to decide whether to run a code block.
  • The condition must ultimately produce or convert to a bool value.
  • If it is true, the block runs; if false, it is skipped.
  • if is not the computer “thinking”; it follows rules that were written in advance.
  • Multiple independent if statements are checked separately.

Next: if...else: What If the Condition Is False?

Your turn

If the condition is false, will the score-increase statement inside the if braces still run?

Have an answer? Click to see the explanation

No. The program skips this branch and continues with the statements that follow it.