If and Else Statement

COS1511 - Introduction To Programming I · Learning C++

If and Else Statement

The if Statement

The if statement allows a C++ program to execute a block of code only when a specified condition is true. If the condition is false, the program skips that block entirely.

Syntax:

if (condition) {
    // code runs only when condition is true
}

Example:

#include <iostream>
using namespace std;

int main() {
    int temperature = 35;
    if (temperature > 30) {
        cout << "It's a hot day!" << endl;
    }
    if (temperature < 0) {
        cout << "Below freezing!" << endl; // skipped
    }
    return 0;
}

Output: It's a hot day!

Remember: In C++, zero is false and any non-zero value is true.

The if-else Statement

The if-else statement provides two mutually exclusive execution paths. One block will always execute — either the if body or the else body.

Syntax:

if (condition) {
    // runs when condition is true
} else {
    // runs when condition is false
}

Example — Pass / Fail:

int score = 47;
if (score >= 50) {
    cout << "Result: PASS" << endl;
} else {
    cout << "Result: FAIL" << endl;
}

Output: Result: FAIL

Watch out: The else block has no condition of its own; it acts as the default case.

The else if Chain

When there are more than two possible outcomes, use an else if chain. The program tests each condition in order and executes the first block whose condition is true.

Syntax:

if (condition1) {
    // runs if condition1 is true
} else if (condition2) {
    // runs if condition1 false AND condition2 true
} else if (condition3) {
    // runs if condition1 & 2 false AND condition3 true
} else {
    // runs if ALL conditions above are false (optional)
}

Example — Grade Calculator:

int mark = 68;
string grade;
if (mark >= 75) {
    grade = "Distinction";
} else if (mark >= 60) {
    grade = "Merit"; // <-- this executes
} else if (mark >= 50) {
    grade = "Pass";
} else {
    grade = "Fail";
}
cout << "Grade: " << grade << endl; // Grade: Merit

Output: Grade: Merit

Tip: The order of conditions matters; check from most specific to least specific.

Nested if Statements

A nested if statement is an if statement placed inside another if (or else) block. This is useful when a second condition only makes sense after the first has passed.

Example — Login System:

bool isLoggedIn = true;
bool isAdmin = false;
if (isLoggedIn) {
    cout << "Welcome back!" << endl;
    if (isAdmin) {
        cout << "Loading admin panel..." << endl;
    } else {
        cout << "Loading user dashboard..." << endl;
    }
} else {
    cout << "Please log in first." << endl;
}

Output:

Welcome back!
Loading user dashboard...

Tip: Avoid deeply nested code to maintain readability. Consider using logical operators instead.

Logical Operators

Logical operators allow you to combine multiple conditions into a single expression.

Example — Voting Eligibility:

int age = 20;
bool isCitizen = true;
if (age >= 18 && isCitizen) {
    cout << "Eligible to vote." << endl;
}

Example — Day Off:

bool isWeekend = false;
bool isHoliday = true;
if (isWeekend || isHoliday) {
    cout << "Day off today!" << endl;
}

The Ternary Operator

The ternary operator is a compact shorthand for a simple if-else statement. It produces a value based on a condition.

Syntax:

variable = (condition) ? valueIfTrue : valueIfFalse;

Example:

string result = (score >= 50) ? "Pass" : "Fail";

Tip: Use the ternary operator for simple assignments; avoid nesting for readability.

Common Pitfalls

Be aware of common mistakes when using if and else statements:

  • Using = instead of ==: This assigns a value instead of comparing it.
  • Missing Braces: Without braces, only the next statement belongs to the if block.
  • Floating-Point Equality: Direct comparison can be unreliable due to imprecision.

Watch out: Always use braces for clarity, even for single-line bodies.

Summary

  • The if statement executes code when a condition is true.
  • The if-else statement provides two paths based on a condition.
  • Use else if for multiple conditions.
  • Nested ifs are useful for dependent conditions.
  • Logical operators combine conditions.
  • The ternary operator offers a compact way to express simple conditions.

Check your understanding

  • What does the if statement do?
  • How does the if-else statement differ from the if statement?
  • What is the purpose of the else if chain?
  • What are the common pitfalls to avoid when using conditional statements?