3.Logical Operators

              Some symbols are used to find the logical values from the conditions. It returns the output as Boolean values either true or false.

There are three logical operators in c++. Let us list out as follows…

‘&&’ – Logical AND Operator

‘||’ – Logical OR Operator

‘!’ – Logical NOT Operator

Each and every logical operator is illustrated with examples….

-------------------------------------------------------------------------------------------------------------------------

Logical AND Operator(&&):

              This operator returns true value when both of the operands are true. The truth table is given below.

Operand1

Operand2

Output

False

False

False

False

True

False

True

False

False

True

True

True

-------------------------------------------------------------------------------------------------------------------------

Logical OR Operator(||):

              Any one of the operands are true, it returns true. Let us create the truth table as follows..

Operand1

Operand2

Output

False

False

False

False

True

True

True

False

True

True

True

True

 Logical NOT Operator (!):

              It is the unary Operator. It makes the operand to negate. For example, if the operand is true, the result is false. Otherwise, true.

Truth table:

Operand

Result

True

False

False

True

 A simple c++ program to use these logical operators as follows

#include <iostream>

using namespace std;

int main() {

    int n1,n2;

    char c;

    cout<<"Enter the number1 :"<<endl;

    cin>>n1;

    cout<<"Enter the number2 :"<<endl;

    cin>>n2;

    //code for Logical AND operator

    if(n1>10 && n2<45) {

        cout<<"n1 is greater than 10 and n2 is less than 45"<<endl;

    }

    else

    {

        cout<<"The numbers are out of range"<<endl;

    }

    cout<<"Enter the character:"<<endl;

    cin>>c;

    //code for Logical OR operator

    if(c=='f' || c=='F')

    {

        cout<<"Yes.that's the character"<<endl;

    }

    else

    {

        cout<<"That's not the character"<<endl;

    }

    //code for logical NOT operator

    if(!true)

   {

      cout<<"False"<<endl;

   }

   else

   {

    cout<<"true"<<endl;

   }

   return(0);

}

Output:

Enter the number1 :

9

Enter the number2 :

45

The numbers are out of range

Enter the character:

f

Yes. That's the character

True

Hope, you understood the concept. You can try many examples based on these logical operators. Keep Coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.