1.3.2 Basic If/Else Statements

Conditional Statements in C++ work exactly the same as Java and similar to other languages:

if (condition) {
    // Statements if true
}
else {
    // Statements if false
}

If Statements

If statements only execute code if the condition is true, otherwise it skips that block of code.

int score = 80;
if (score > 75) {
    // Prints because score is greater than 75
    cout << "Score is greater than 75" << endl;
} 

Else Statement

Else statements only execute when the if condition is false. With an if/else combination, one of the coding blocks will always execute, but never both.

int score = 80;
if (score > 85) {
    // Skips this block
    cout << "Score is greater than 85" << endl;
}
else {
    // Executes this block
    cout << "Score is not greater than 85" << endl;
}

Else If Statements

With an else if clause, the code will evaluate the else if clause only when the previous if statements are negative. If it evaluates to true, the coding block will be executed.

int score = 80;
if (score >= 82) {
    // Doesn't execute this block
    cout << "Score is greater than or equal to 82" << endl;
}
else if (score > 78) {
    // Executes this block of code
    cout << "Score is not greater than 78 but less than 82" << endl;
} 
else {
    // Skips this block since the above section was true
    cout << "Score is not greater than 78" << endl;
}

Summary

Below is a summary of the options you can use with if statements.

ClauseUse

if (condition)

Required to start conditional block and can only have one

else if (condition)

Optional and can have as many as needed; Follows if statement and before else clause

else

Optional and can have only one; must be the last clause and contain no conditional statement.

Try This Example

Last updated