C++ if else statement



This article explains the C++ if else statement.

The C++ if else statement is a way of decision making in C++ . The most basic explanation of the if statement is that “if” a “given condition” occurs then “do this“. The condition and the corresponding action are defined by us. The if statement handles the rest.

As an alternative, there is the switch statement which is another way of decision making in making C++. It performs better in certain scenarios so be sure to check it out too.


C++ if statement

Syntax

The simplest and most common form of the C++ if statement.

if (condition) {
    // code statement(s)
}

As explained earlier, if the given condition evaluates to the boolean value of “True” then the code statements within the code block will execute. If the condition is false, the code block (the code within the curly brackets) is ignored.

Example

The “conditions” for if statements are almost always made using C++ comparison operators. They’re just the regular operators you use in arithmetic plus a few extra ones.

Below is a simple demonstration.

int main () {
    int x;

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

    if (x > 5) {
            cout << "Greater than 5";
    }
}
Enter number: 8
Greater than 5

The above code checks to see the “if” the number entered by the user is greater than 5. If “yes” or “true” then the code block where the cout keyword is located, is executed. If not, nothing happens and the flow of the program moves to the line after the closing curly bracket.


C++ If…else statement

Syntax

The code block contained within the brackets of the else statement will run if none of the conditions in the if statement have been met.

if (condition) {
    // code statement(s)
}
else (condition) {
    // code statement(s)
}

You can think of it as a default code block that executes in the absence of others.

Example

The following example is simply an extension of the previous one. It basically “completes” the if statement in a way. With the else statement as well, there will always be an output, whether the condition was met or not.

int main () {
    int x;

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

    if (x > 5) {
            cout << "Greater than 5";
    }
    else {
        cout << "Less than 5";
    }
}
Enter number: 2
Less than 5

The lack of an else statement can sometimes confuse the user because there will never be any output or corresponding action. Don’t use it unnecessarily though.


C++ if…else…else if statement

Syntax

The full form of if statement, utilizing all the different possible keywords. The dots are included there because there is no limit to the number of else if statements that one may have.

if (condition) {
    // code statement(s)
}
else if (condition) {
    // code statement(s)
}
..
..
..
else {
    // code statement(s)
}

The purpose of else if is to add more conditions on to the if statements. It’s inefficient to have multiple if statements, hence why we have else if.

Example

A new example to demonstrate the use of all three statements working together.

int main () {
    bool x = true;

    if (x == true) {
            cout << "X is True";
    }
    else if (x == false) {
        cout << "X is False";
    }
    else {
        cout << "X is neither True or False";
    }
}

The else statement will trigger if the value is neither true or false. Perhaps there was an error no outcome was reached. And it’s for these scenarios that the else statement really comes in handy, for a third “unexpected” outcome.

We didn’t cover a 4th possibility, if...elseif, but all you have to do is leave the “else” statement out as it isn’t a requirement for the elseif statement.


Combining multiple conditions

You can use more than just one condition in a if statement. You basically just create a longer expression, using logical operators to connect the various conditions.

The most commonly used operators for such purposes are the and and or logic operators, represented by && and || respectively. The and operators returns true if both conditions are true, whereas the or operator returns true if even one of the conditions are true.

#include <iostream>
using namespace std;

int main () {
    int x;

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

    if ((x > 0) &amp;&amp; (x < 101)) {
        cout << "X is a number between 0 and 101";
    }
}
Enter number: 6
X is a number between 1 and 100

Both conditions are necessary to determine whether the number is between 0 and 101. Leaving out either one would include an infinite number of values.

Be sure to handle the round brackets properly. It’s the round brackets that define the expression, so make sure everything is safely enclosed in it.


Nested if statements

You can increase the power and complexity of your decision making by “nesting” if statement within each other.

Below is pretty good example for understanding how nested loops can come in handy.

int main () {
    int x, y;

    cout << "Enter number x: ";
    cin >> x;
    cout << "Enter number y: ";
    cin >> y;

    if (x > 0) {
        if (y > 0) {
            cout << "X and Y are both positive";
        }
        if (y < 0) {
            cout << "X is positive, Y is negative";
        }
    }
}
Enter number x: 6
Enter number y: -8
X is positive, Y is negative

There is no real limit to the number of nested layers that you can create, but if you have more than 3 if statements nested within each other, it’s probably time to rethink your approach.


This marks the end of the C++ if else statement article. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the article content can be asked in the comments section below.

Leave a Reply

Your email address will not be published. Required fields are marked *