C++ If...Else

Making decisions in your C++ programs

🤔 What is C++ If...Else?

C++ if...else statements allow your program to make decisions and execute different code blocks based on conditions, making your programs interactive and intelligent.


#include <iostream>
using namespace std;

int main() {
    int age = 18;
    
    if (age >= 18) {
        cout << "You are an adult!" << endl;
    } else {
        cout << "You are a minor!" << endl;
    }
    
    return 0;
}
                                    

Output:

You are an adult!

Key If...Else Concepts

🔍

If Statement

Execute code when condition is true

if (condition) {
    // code here
}
🔄

Else Statement

Execute code when condition is false

else {
    // alternative code
}
🔗

Else If

Check multiple conditions

else if (condition2) {
    // another option
}
🎯

Nested If

If statements inside other if statements

if (outer) {
    if (inner) { }
}

🔹 Basic If Statement

The if statement is the simplest form of conditional execution in C++, allowing your program to make decisions based on boolean expressions. It evaluates a condition inside parentheses; if true, the associated block of code runs. For example, checking if a score is above a passing threshold (like 85) and printing "Good job! You passed". This fundamental construct enables responsive, dynamic behavior in programs, from validating user input to controlling game logic. Mastering if statements is essential for implementing logic and branching, forming the basis of more complex control structures like else and else if.

#include <iostream>
using namespace std;

int main() {
    int score = 85;
    
    if (score >= 90) {
        cout << "Excellent! Grade A" << endl;
    }
    
    if (score >= 70) {
        cout << "Good job! You passed" << endl;
    }
    
    cout << "Your score: " << score << endl;
    
    return 0;
}

Output:

Good job! You passed

Your score: 85

🔹 If...Else Statement

The if...else statement extends basic conditionals by providing an alternative execution path when the initial condition is false, enabling binary decision-making. For instance, to determine if a number (like 7) is odd or even, the if block can check divisibility by 2, and the else block handles the opposite case, outputting "7 is odd". This structure is ubiquitous in programming for tasks like user authentication, error handling, and feature toggling, making programs more flexible and robust by accounting for multiple possible outcomes within a clear, readable syntax.

#include <iostream>
using namespace std;

int main() {
    int number = 7;
    
    if (number % 2 == 0) {
        cout << number << " is even" << endl;
    } else {
        cout << number << " is odd" << endl;
    }
    
    return 0;
}

Output:

7 is odd

🔹 Else If Statement

The else if construct allows sequential evaluation of multiple conditions, perfect for scenarios with more than two distinct outcomes, such as grading systems or menu selections. Instead of nesting multiple if statements, else if chains provide a cleaner, more efficient way to check a series of possibilities. For example, converting a numerical score to a letter grade (like 'C' for a score in the 70s) involves checking score ranges in order until a match is found. This improves code organization and performance by stopping at the first true condition, essential for complex decision trees in applications ranging from business logic to game AI.

#include <iostream>
using namespace std;

int main() {
    int grade = 78;
    
    if (grade >= 90) {
        cout << "Grade: A" << endl;
    } else if (grade >= 80) {
        cout << "Grade: B" << endl;
    } else if (grade >= 70) {
        cout << "Grade: C" << endl;
    } else if (grade >= 60) {
        cout << "Grade: D" << endl;
    } else {
        cout << "Grade: F" << endl;
    }
    
    return 0;
}

Output:

Grade: C

🔹 Nested If Statements

Nested if statements place one conditional inside another, enabling detailed, multi-layered logic checks for sophisticated decision-making. For example, to verify driving eligibility, you might first check if a person is an adult (age ≥ 18) and then, within that block, confirm they have a valid license, ultimately printing "You can drive!". This technique is powerful for validating combinations of conditions, handling hierarchical data, or implementing complex business rules. However, over-nesting can reduce readability, so it should be used judiciously, often complemented by logical operators (&&, ||) for clarity and maintainability.

#include <iostream>
using namespace std;

int main() {
    int age = 20;
    bool hasLicense = true;
    
    if (age >= 18) {
        cout << "You are an adult." << endl;
        
        if (hasLicense) {
            cout << "You can drive!" << endl;
        } else {
            cout << "You need a license to drive." << endl;
        }
    } else {
        cout << "You are too young to drive." << endl;
    }
    
    return 0;
}

Output:

You are an adult.

You can drive!

🧠 Test Your Knowledge

What will be printed if x = 5?
if (x > 3) cout << "Big"; else cout << "Small";