How to Add Multiple Conditions for if Statement in C++?

In C++, an if statement is used to decide whether a specific block of code should execute, depending on a given condition. It usually evaluate a single expression to check condition. In this article, we will learn how to add multiple conditions as a single expression for an if statement in C++.

Multiple Conditions for if Statement in C++

To check multiple conditions in an if statement, we can use logical operators within an if statement to evaluate the conditions. The most commonly used logical operators are:

  • logical AND (&&): If we want the code block to execute only if both the given conditions are true, the && operator is used.
  • logical OR (||): If we want the code block to execute even if at least one of the condition is true, then || The operator is used.

Syntax to Define if Statement With Multiple Conditions

if ((condition1 && condition2) || condition3) {
// Code to execute if both condition1 and condition2 are true
// or condition 3 is true
}

Note: When combining && and || always use parentheses to explicitly define the precedence of operations that makes code more readable and prevents logical errors.

C++ Program to Demonstrate the if Statement With Multiple Conditions

The below program implements the if statement with multiple conditions.

C++
// C++ program to implement if statement with multiple
// conditions
#include <iostream>
using namespace std;

int main()
{
    // Declare and initialize an integer variable.
    int val = 50;

    // Declare and initialize a boolean variable.
    bool isPossible = true;

    // Check multiple conditions in a single if statement
    // i.e. if num is either 50 or 100 and isPossible is
    // true.
    if ((val == 50 || val == 100) && isPossible) {
        cout << "Given Value is either 50 or 100 and it "
                "is a possible number."
             << endl;
    }

    return 0;
}

Output
Given Value is either 50 or 100 and it is a possible number.

Time Complexity: O(1)
Auxilliary Space: O(1)

Note: The expression in which the multiple logical operations are used is evaluated using short circuiting concept which in some cases, reduce the number of condition evaluation.