Hit enter after type your search item

5 Programs to Learn C++ OR (||) operator

What is C++ OR operator

  • OR is a logical operator in C++
  • The OR is denoted by || (two pipe signs)
  • The OR is used to evaluate two statements
  • If both statements are true, it returns 1 i.e. true
  • If one statement is true and the other is false, it returns 1 i.e. true
  • In case, both statements are false – it reruns 0 i.e. false
  • Unlike the AND operator (&&) that reruns false if any of the statement is false

A simple example of using OR (||) operator

In this example, we have two int type variables. We will check its equality with the || operator and display three results. See the C++ program below:


Output:

CPP-or-statement

Using OR operator in if statement examples

The following short snippet of code in C++ shows using OR logical operator (||) in the if statement.

The three programs below show the result when:

  • both conditions are true
  • one condition is true and the other is false
  • both are false

Program 1


Output:

True

As the value of x is less than or equal to 5 and the value of y is greater than or equal to 10, so both conditions are true and the output is True.

Program 2


Output:

True

As the value of x is not greater than 5, our first condition is false. However, the y value is greater than or equal to 10, so it’s true; so end result is true.

Program 3


Output:

False

As neither value of x is greater than 5 nor the value of y is less than 10 – so both conditions are false. As a result, the else part executed that displayed “False”.

Using two OR operators examples

We are extending our above example to show you using the two OR operators in a single if statement.

For that, we have a third char-type variable with an initial value. It’s value is also checked in the if statement as follows:


Output:

True

Although, the x and y conditions are false, however, the chr value is ‘y’, so it is true. The end result is True.

 

This div height required for enabling the sticky sidebar