Home C++ if statement in C++ tutorial

if statement in C++ tutorial

The if statement in C++ is a conditional control structure that allows you to execute code based on whether a specified condition is true or false.

It’s one of the fundamental tools for decision-making in a program, allowing you to control the flow based on conditions.

Basic Syntax of the if Statement

if (condition) {
    // Code to execute if condition is true
}
  • Condition: An expression that evaluates to true or false.
  • Code block: Executes only if the condition is true.

1. Basic if Statement

A simple if statement that checks if a number is positive.

#include <iostream>
using namespace std;

int main() {
    int num = 10;

    if (num > 0) {
        cout << "The number is positive." << endl;
    }

    return 0;
}

Explanation:

  • num > 0 is the condition. If it’s true, “The number is positive” is printed.

Output:

The number is positive.

2. if Statement with else

Using if with else allows you to execute an alternative code block when the condition is false.

#include <iostream>
using namespace std;

int main() {
    int num = -5;

    if (num > 0) {
        cout << "The number is positive." << endl;
    } else {
        cout << "The number is not positive." << endl;
    }

    return 0;
}

Explanation:

  • If num > 0 is false, the code in the else block executes.

Output:

The number is not positive.

3. if-else if-else Statement

An if-else if-else statement allows multiple conditions to be checked in sequence.

#include <iostream>
using namespace std;

int main() {
    int num = 0;

    if (num > 0) {
        cout << "The number is positive." << endl;
    } else if (num < 0) {
        cout << "The number is negative." << endl;
    } else {
        cout << "The number is zero." << endl;
    }

    return 0;
}

Explanation:

  • The code checks if num is positive, negative, or zero, and executes the appropriate block.

Output:

The number is zero.

4. Nested if Statements

You can place one if statement inside another, known as nested if statements.

#include <iostream>
using namespace std;

int main() {
    int num = 15;

    if (num > 0) {
        if (num % 2 == 0) {
            cout << "The number is positive and even." << endl;
        } else {
            cout << "The number is positive and odd." << endl;
        }
    } else {
        cout << "The number is not positive." << endl;
    }

    return 0;
}

Explanation:

  • The outer if checks if num is positive.
  • The inner if checks if num is even or odd.

Output:

The number is positive and odd.

5. Checking Multiple Conditions with Logical Operators

You can combine multiple conditions in an if statement using logical operators (&&, ||).

#include <iostream>
using namespace std;

int main() {
    int age = 20;
    bool hasID = true;

    if (age >= 18 && hasID) {
        cout << "You are allowed entry." << endl;
    } else {
        cout << "Entry denied." << endl;
    }

    return 0;
}

Explanation:

  • age >= 18 && hasID checks if both conditions are true before allowing entry.

Output:

You are allowed entry.

6. Using if with Comparison Operators

The if statement often uses comparison operators (==, !=, >, <, >=, <=) to compare values.

#include <iostream>
using namespace std;

int main() {
    int a = 5, b = 10;

    if (a == b) {
        cout << "a is equal to b." << endl;
    } else if (a != b) {
        cout << "a is not equal to b." << endl;
    }

    return 0;
}

Explanation:

  • a == b checks if a is equal to b.
  • a != b checks if a is not equal to b.

Output:

a is not equal to b.

7. Using if with User Input

You can use an if statement to validate user input.

#include <iostream>
using namespace std;

int main() {
    int number;

    cout << "Enter a number: ";
    cin >> number;

    if (number % 2 == 0) {
        cout << "The number is even." << endl;
    } else {
        cout << "The number is odd." << endl;
    }

    return 0;
}

Explanation:

  • The if statement checks if number is divisible by 2 to determine if it’s even or odd.

Sample Output:

Enter a number: 7
The number is odd.

8. Using if to Check Ranges

An if statement can check if a value falls within a specific range.

#include <iostream>
using namespace std;

int main() {
    int score;

    cout << "Enter your score: ";
    cin >> score;

    if (score >= 90) {
        cout << "Grade: A" << endl;
    } else if (score >= 75) {
        cout << "Grade: B" << endl;
    } else if (score >= 60) {
        cout << "Grade: C" << endl;
    } else {
        cout << "Grade: F" << endl;
    }

    return 0;
}

Explanation:

  • The if-else if ladder assigns a grade based on the range in which score falls.

Sample Output:

Enter your score: 85
Grade: B

9. Ternary Operator as a Short if-else Alternative

The ternary operator (? 🙂 can be used as a shorthand for a simple if-else statement.

#include <iostream>
using namespace std;

int main() {
    int num = 10;
    string result = (num > 0) ? "Positive" : "Non-positive";
    cout << "Result: " << result << endl;
    return 0;
}

Explanation:

  • (num > 0) ? “Positive” : “Non-positive” is a shorter way to write if-else.

Output:

Result: Positive

10. Summary Table of if Statement Uses

Use Case Code Example Description
Basic if statement if (x > 0) {…} Executes code if condition is true
if-else statement if (x > 0) {…} else {…} Executes alternative code if condition is false
if-else if-else statement if (…) {…} else if (…) {…} else Checks multiple conditions in sequence
Nested if if (…) { if (…) {…} } Places if inside another if
Multiple conditions if (x > 0 && y > 0) {…} Combines conditions with logical operators
Comparison operators if (x != y) {…} Uses comparison operators to compare values
Validate user input if (x % 2 == 0) {…} Checks user input for even or odd
Range checking if (score >= 90) {…} Checks if a value falls within a range
Ternary operator string result = (x > 0) ? “Yes” : “No”; Short if-else replacement

Complete Example

This example demonstrates how if statements can be used to handle various conditions, including user input, comparison, and nested if.

#include <iostream>
using namespace std;

int main() {
    int age;
    bool isMember;

    cout << "Enter your age: ";
    cin >> age;

    cout << "Are you a club member? (1 for Yes, 0 for No): ";
    cin >> isMember;

    if (age >= 18) {
        if (isMember) {
            cout << "You are eligible for the premium club." << endl;
        } else {
            cout << "You are eligible for the standard club." << endl;
        }
    } else {
        cout << "You are not eligible for the club." << endl;
    }

    return 0;
}

Explanation:

  • The program checks if the user is at least 18.
  • If age >= 18 is true

, it then checks if the user is a member.

  • Based on the membership status, the program decides the type of club access.

Sample Output:

Enter your age: 21
Are you a club member? (1 for Yes, 0 for No): 1
You are eligible for the premium club.

The if statement in C++ is essential for making decisions based on conditions, allowing your program to respond dynamically to different scenarios.

You may also like