C++

Selection Statements: If, If-Else, and Nested If in C++

In C++, Selection Statements (also known as Decision Control Statements) allow a program to deviate from its linear, top-to-bottom execution path. By evaluating conditions, the program can choose to execute specific blocks of code while skipping others. This simulates "logical thinking" in software.

1. The Theory: Control Flow and Boolean Logic

At the hardware level, every decision in C++ boils down to a Binary Branch. The CPU evaluates a condition (usually involving relational or logical operators) and produces a result of either True (1) or False (0).

How C++ Evaluates Truth:

  • Explicit Boolean: Using true or false.

  • Numeric Evaluation: In C++, any non-zero value (positive or negative) is treated as True. Only zero (0) is treated as False.

    Example: if (5) will execute the block, but if (0) will skip it.

2. The if Statement (Simple Selection)

The if statement is the most basic form of decision-making. It executes a block of code only if the specified condition is true.

  • Theory: If the condition is false, the program simply ignores the entire block associated with the if and moves to the next line of code outside the braces.

  • Syntax:

    C++
    if (condition) {
        // Code to execute if condition is true
    }
    

3. The if-else Statement (Binary Selection)

The if-else structure provides an alternative path. It ensures that exactly one of two blocks will execute.

  • Theory: This creates a "mutual exclusion." If the condition is true, the if block runs and the else block is skipped. If the condition is false, the if block is skipped and the else block runs. There is no scenario where both (or neither) run.

  • Syntax:

    C++
    if (condition) {
        // Block A
    } else {
        // Block B
    }
    

4. Nested if Statements (Multi-level Selection)

A Nested If is an if statement placed inside another if or else block.

  • Theory: This is used when a second condition needs to be checked only after a first condition has passed. It creates a hierarchy of requirements.

  • The "Dangling Else" Problem: In nested structures, C++ always associates an else with the closest preceding if that does not already have an else. To avoid confusion, always use curly braces {} to clearly define which else belongs to which if.

5. Practical Code Example

This program evaluates a student's eligibility for a scholarship based on two conditions: their Grade Point Average (GPA) and their attendance.

#include <iostream>
using namespace std;

int main() {
    float gpa;
    int attendance;

    cout << "Enter your GPA (0.0 - 4.0): ";
    cin >> gpa;
    cout << "Enter your attendance percentage: ";
    cin >> attendance;

    // Outer If: Check GPA
    if (gpa >= 3.5) {
        
        // Inner (Nested) If: Check Attendance
        if (attendance >= 90) {
            cout << "Congratulations! You qualify for a full scholarship." << endl;
        } else {
            cout << "You have the grades, but your attendance is too low for the scholarship." << endl;
        }

    } else if (gpa >= 3.0) {
        // This runs if the first 'if' was false but this is true
        cout << "You qualify for a partial scholarship." << endl;
    } else {
        // This runs if all previous conditions were false
        cout << "Sorry, you do not qualify for a scholarship at this time." << endl;
    }

    return 0;
}

6. Comparison Table: Decision Structures

StructureBest Used ForExecution Path
ifA single optional action.0 or 1 path taken.
if-elseTwo mutually exclusive choices.Exactly 1 path taken.
if-else ifMultiple independent choices.Exactly 1 path taken (first match).
Nested ifDependent/conditional requirements.Paths depend on multiple layers.

7. Performance and Optimization (Long Theory)

When implementing selection statements in large projects, the order of conditions matters:

  1. Probability-Based Ordering: In an if-else if chain, place the condition most likely to be true at the top. This saves the CPU from evaluating multiple false conditions.

  2. Expensive Operations: Place simple comparisons (like x == 5) before expensive function calls in a logical AND (&&) condition. Due to Short-Circuit Evaluation, if the simple comparison fails, the expensive function won't be called.

  3. Refactoring: If you find yourself nesting more than 3 levels deep, it is often a sign that the code should be simplified using a switch statement or by breaking the logic into separate functions.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now