Geek Slack

Learn C++
About Lesson


C++ If … Else


C++ If … Else

The if ... else statement in C++ allows you to execute a block of code based on the evaluation of a condition. It provides control over the flow of your program by deciding whether to execute one block of code or another.

1. Basic if … else Statement

The basic syntax of the if ... else statement:

#include <iostream>

int main() {
    int num = 10;

    if (num % 2 == 0) {
        std::cout << num << " is even." << std::endl;
    } else {
        std::cout << num << " is odd." << std::endl;
    }

    return 0;
}

2. Nested if … else Statements

You can nest if ... else statements to handle more complex conditions:

#include <iostream>

int main() {
    int num = 10;

    if (num > 0) {
        if (num % 2 == 0) {
            std::cout << num << " is a positive even number." << std::endl;
        } else {
            std::cout << num << " is a positive odd number." << std::endl;
        }
    } else if (num < 0) {
        std::cout << num << " is a negative number." << std::endl;
    } else {
        std::cout << num << " is zero." << std::endl;
    }

    return 0;
}

3. Using else if

You can use else if to check multiple conditions:

#include <iostream>

int main() {
    int score = 85;

    if (score >= 90) {
        std::cout << "A grade." << std::endl;
    } else if (score >= 80) {
        std::cout << "B grade." << std::endl;
    } else if (score >= 70) {
        std::cout << "C grade." << std::endl;
    } else if (score >= 60) {
        std::cout << "D grade." << std::endl;
    } else {
        std::cout << "F grade." << std::endl;
    }

    return 0;
}

Conclusion

The if ... else statement is fundamental in C++ for controlling program execution based on conditions. This chapter covered its basic usage, nesting if ... else statements, using else if for multiple conditions, and provided examples to illustrate their application. Mastering if ... else statements enables you to write more dynamic and responsive programs.

Join the conversation