Flash cards
Review the key moves
What is the main idea behind C++ If ... Else?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
___ ( condition ) {Put the learning moves in the order that makes the concept easiest to apply.
C++ Conditions and If Statements
You already know that C++ supports familiar comparison conditions from mathematics, such as:
- Less than: a < b
- Less than or equal to: a <= b
- Greater than: a > b
- Greater than or equal to: a >= b
- Equal to: a == b
- Not equal to: a != b
These conditions are used to perform different actions depending on whether something is true or false.
C++ has the following conditional statements:
- Use if to specify a block of code to be executed, if a condition is true
- Use else to specify a block of code to be executed, if the same condition is false
- Use else if to specify a new condition to test, if the first condition is false
- Use switch to specify many alternative blocks of code to be executed
The if Statement
Use the if statement to specify a block of C++ code to be executed if a condition is true .
Syntax
if ( condition ) {
// block of code to be executed if the condition is true
}Note that if is written in lowercase letters. Uppercase letters ( If or IF ) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the condition is true , we print a message:
Example
if (20 > 18) {
cout << "20 is greater than 18";
}We can also use variables in conditions:
Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}In the example above, we use two variables, x and y , to test whether x is greater than y . Because 20 is greater than 18, the condition is true, and the message is printed.
Using a Boolean Variable
Since the condition in an if statement must be either true or false, you can store the result in a boolean variable instead of writing the comparison directly:
Example
int x = 20;
int y = 18;
bool isGreater = x > y;
if (isGreater) {
cout << "x is greater than y";
}This can make your code easier to read, especially when the condition is complex or used more than once.