C++ Conditional Statements: if, else, and switch

In programming, we often need our code to make decisions and perform different actions based on different conditions. Think about how a game responds when you press a button, or how a login screen reacts to a correct or incorrect password. This decision-making logic is controlled by conditional statements. For any C++ beginner, mastering conditionals like if, else if, else, and switch is the key to creating dynamic and intelligent programs.

πŸ”Ή Quick Reference: C++ Conditional Statements

StatementPurposeWhen to Use It
ifExecutes code only if a condition is true.For a single, one-off check.
if-elseChooses between two different blocks of code.For an “either-or” decision.
if-else if-elseChooses from multiple, mutually exclusive conditions.For a chain of related checks.
switchSelects a block of code from a list of constant values.As a clean alternative to a long if-else if ladder.

1. The if Statement: The Basic Gatekeeper

The if statement is the simplest conditional. It checks if a condition is true, and if it is, it executes a block of code. If the condition is false, the block is simply skipped.

Analogy: “If it is raining, take an umbrella.” You only take the umbrella if the condition (raining) is met.

#include <iostream>
int main() {
    int score = 95;
    // The condition inside the parentheses is evaluated.
    // Since 95 is greater than 90, the condition is true.
    if (score > 90) {
        // This block of code will only execute if the condition is true.
        std::cout << "Congratulations! You earned an A grade!" << std::endl;
    }
    std::cout << "End of program." << std::endl;
    return 0;
}

Output

Congratulations! You earned an A grade!
End of program.

πŸ“ Try it Yourself: Write a program that asks a user for their age. If their age is 18 or greater, print a message that says, “You are eligible to vote.”

2. The if-else Statement: The Two-Way Street

The if-else statement provides an alternative path. If the condition is true, the if block runs. If it’s false, the else block runs. One of the two blocks is guaranteed to execute.

Analogy: “If you have a ticket, enter the theater. Otherwise (else), go to the ticket counter.”

#include <iostream>
int main() {
    int number = 7;
    // Check if the number is even.
    // The modulus operator (%) gives the remainder of a division.
    if (number % 2 == 0) {
        // This block runs if the remainder is 0 (the number is even).
        std::cout << "The number is even." << std::endl;
    } else {
        // This block runs if the condition is false (the number is odd).
        std::cout << "The number is odd." << std::endl;
    }
    return 0;
}

Output

The number is odd.

πŸ“ Try it Yourself: Create a simple password checker. Ask the user to enter a password. If it matches a secret password (e.g., “secret123”), print “Access Granted.” Otherwise, print “Access Denied.”

3. The if-else if-else Ladder: The Multi-Choice Path

When you need to check a series of related conditions, you can chain them together using an if-else if-else ladder. The first condition that evaluates to true will have its block executed, and the rest of the chain will be skipped.

#include <iostream>
int main() {
    int score = 85;
    // The program checks these conditions from top to bottom.
    if (score >= 90) {
        std::cout << "Grade: A" << std::endl;
    } else if (score >= 80) {
        // This condition is checked only if the first one was false.
        // Since 85 >= 80 is true, this block runs, and the ladder stops.
        std::cout << "Grade: B" << std::endl;
    } else if (score >= 70) {
        std::cout << "Grade: C" << std::endl;
    } else {
        // This runs only if all previous conditions were false.
        std::cout << "Grade: F" << std::endl;
    }
    return 0;
}

Output

Grade: B

πŸ“ Try it Yourself: Write a program that asks for a temperature. If it’s below 0, print “Freezing.” If it’s between 0 and 20, print “Cool.” If it’s above 20, print “Warm.”

4. The switch Statement: The Clean Alternative

The switch statement is a clean alternative to a long if-else if ladder when you are checking a single variable against a list of specific, constant integer or character values.

Analogy: A vending machine. You provide one value (your choice), and the machine gives you a specific item based on that choice.

#include <iostream>
int main() {
    int choice = 2;
    // The switch statement evaluates the 'choice' variable.
    switch (choice) {
        // It checks if choice is equal to 1.
        case 1:
            std::cout << "You selected Option 1: View Profile." << std::endl;
            break; // The 'break' keyword exits the switch statement.
        
        // Since choice is 2, this case matches.
        case 2:
            std::cout << "You selected Option 2: Edit Settings." << std::endl;
            break; // Without break, it would "fall through" and execute case 3 as well!
        case 3:
            std::cout << "You selected Option 3: Log Out." << std::endl;
            break;
            
        // If no other case matches, the default block runs.
        default:
            std::cout << "Invalid choice. Please try again." << std::endl;
            break;
    }
    return 0;
}

Output

You selected Option 2: Edit Settings.

πŸ“ Try it Yourself: Write a program that asks the user to enter a number from 1-3. Use a switch statement to print “Gold,” “Silver,” or “Bronze” based on their input.

πŸ”Ή Frequently Asked Questions (FAQ)

Q: What is the difference between if-else if and switch?
A: Use an if-else if ladder for complex conditions involving ranges (e.g., score > 90) or logical operators. Use a switch statement for checking a single variable against a list of specific, constant integer or character values. A switch is often cleaner and more efficient for this specific task.

Q: What happens if I forget the break keyword in a switch statement?
A: This is a common bug called “fall-through.” If you omit break, the program will execute the code for the matching case and then continue executing the code for all the subsequent cases until it hits a break or the end of the switch block.

Q: Can I use a variable in a case label?
A: No. The value in a case label must be a constant expression (a literal like 5, 'A', or a const variable). It cannot be a regular variable.

Q: Is the default case required in a switch?
A: It’s not required, but it is highly recommended. It handles any unexpected values and can help prevent bugs.

Leave a Comment

About RadiantRiva

Your go-to resource for coding tutorials, developer guides, and programming tips.

Learn More

Quick Links

Follow Us

Newsletter

Get coding tips, tutorials, and updates straight to your inbox.