Introduction
Sometimes you want to perform more than one test for a
decision. You may want to combine two or more checks on values and perform a
certain action only when they’re all true. For example, you may only want to go
to watch a movie if you’re feeling well and it’s a weekend. These sorts
of situations demand use of logical operators.
There are three logical operators available in C -
&&,|| and !.
1. Logical AND
&& Operator
- binary operator that combines two logical expressions—that is, two expressions that evaluate to true or false.
- Returns true when both the conditions are true; return false when any of the conditions or both are false.
Syntax :
Expression1
&& Expression2
This expression evaluates to true
if both expressions Expression1 and Expression2 evaluate to true. If either or
both of the expressions are false, the result of the operation is false.
Example:
if(marks >=60 && age < =80)
printf("Grade : B\n");
2. Logical OR
|| Operator
- binary operator that combines two logical expressions—that is, two expressions that evaluate to true or false.
- If either or both expressions of the || operator are true, the result is true. The result is false only when both operands are false.
Syntax :
Expression1
|| Expression2
This expression evaluates to true
if either or both expressions Expression1 and Expression2 evaluate to true. If
both expressions are false, the result of the operation is false.
Example:
if(marks >=60 || age < =80)
printf("Grade : B\n");
3. Logical NOT
! Operator
- The ! operator is a unary operator, because it applies to just one operand.
- The logical NOT operator reverses the value of a logical expression: true becomes false, and false becomes true
Syntax :
!(expression)
If expression is true, it becomes false; if it is false, it becomes
true.
Example:
int marks=100;
if(!marks)
printf("You didn’t received
100% marks.\n");
No comments:
Post a Comment