If-Else Statements in C++ tutorial

9/12/2025
All Articles

If-Else Statements in C++ cplus

If-Else Statements in C++ tutorial

If-Else Statements in C++

If-Else statements are fundamental decision-making constructs in C++ that allow your program to execute certain code blocks conditionally, based on whether an expression evaluates to true or false.


🔹 Syntax of If Statement

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

Example:

#include <iostream>
using namespace std;

int main() {
    int age = 20;

    if (age >= 18) {
        cout << "You are eligible to vote." << endl;
    }

    return 0;
}

Output:

You are eligible to vote.

🔹 Syntax of If-Else Statement

if (condition) {
    // Code if condition is true
} else {
    // Code if condition is false
}

Example:

#include <iostream>
using namespace std;

int main() {
    int number = 5;

    if (number % 2 == 0) {
        cout << "Even number" << endl;
    } else {
        cout << "Odd number" << endl;
    }

    return 0;
}

Output:

Odd number

🔹 If-Else If Ladder

This is used when you want to test multiple conditions.

if (condition1) {
    // Code if condition1 is true
} else if (condition2) {
    // Code if condition2 is true
} else {
    // Code if none of the above is true
}

Example:

#include <iostream>
using namespace std;

int main() {
    int marks = 85;

    if (marks >= 90) {
        cout << "Grade A" << endl;
    } else if (marks >= 75) {
        cout << "Grade B" << endl;
    } else {
        cout << "Grade C" << endl;
    }

    return 0;
}

Output:

Grade B

Best Practices

  • Always use clear and simple conditions.

  • Avoid deeply nested if-else chains; use switch if suitable.

  • Use braces {} even for single statements to prevent logical errors.

Article