If...

Use if when you want the computer to choose what to do based on a situation.


Ask a question

int number = 15;

if (number > 10) {
    std::cout << "It is greater than 10!" << std::endl;
}

In plain English:

Remember that number is 15

If (number is greater than 10) {
    print "It is greater than 10!"
}

No! (else)

If the question is false, use else.

if (number > 10) {
    std::cout << "It is big!" << std::endl;
} else {
    std::cout << "It is small or equal!" << std::endl;
}

Translation:

Remember that number is 15

If (number is greater than 10) {
    print "It is big!"
} otherwise {
    print "It is small or equal!"
}

Ask multiple questions (else if)

When one question is not enough, you can ask another.

if (number > 20) {
    std::cout << "It is greater than 20!" << std::endl;
} else if (number > 10) {
    std::cout << "It is greater than 10 and 20 or less!" << std::endl;
} else {
    std::cout << "It is 10 or less!" << std::endl;
}

Translation:

If (number is greater than 20) { ... }
Otherwise, if (number is greater than 10) { ... }
Otherwise { ... }

The secret of brackets

  • Parentheses ( ) contain the question.
  • Braces { } contain the actions if the question is true.

The question ends when the braces close. Now you can give C++ smart choices.