Operators in C Language | Part-3

Relational Operator

Relational operators are used to perform a logical test or create a condition. List of the logical operator is as given below...

Relational opertor Meaning
> Greater Than
< Less Than
>= Greater Than or Equal to
<= Less Than or Equal to
== Equal to
!= Not euqal
  1. Every relational operator returns true or false.
  2. In C any non-zero is treated as true and zero is treated as false.
  3. In C if any expression evaluated true then system returns 1 otherwise return 0.
  4. Relational operator are evaluated from left to right.

Example-1


printf("%d",5>2); //print 1

Example-2


printf("%d",5>2>1); //print 0
//first 5>2 evaluated true and returns 1 and then result of this expression is compared with next 1, that is evaluated false.

Logical Operator

  1. &&(And) ||(Or) !(not) are the 3 logical operators.
  2. &&(and), || (or) are used to combine two or more conditions.
  3. Each condition can be true or false, so what will be the output of the combination made by logical operator &&(and) , ||(or). This is decided by truth table.
  4. truth table is the combination of conditionsa and their results as shown below...
C1 C2 C1 && C2 C1 || C2
F F F F
F T F T
T F F T
T T T T

Examples of Relational Operator


int a = 5, b = 6, c;
c = a > 2 && b > 3;
printf("%d %d %d",a,b,c);//5 6 1 


int a = 5 , b = 6, c;
c = a > 2 || b < 8;
printf("%d %d %d",a,b,c);//5 6 1 


printf("%d",5 && 6);//1

//In c any non-zero is treated as true. because 5 and 6 are non-zero so both are true,so the result is true that is 1. 


int a = 5, b = 6, c;
c = a > 2 || ++b;
printf("%d %d %d",a,b,c);//5 6 1

Logical operator are short circuit operator means or(||) operator returns true as soon as if first condtion is true, and(&&) operator returns false as soon as first condition is evaluated false.

Not operator

  1. Not operator just negates the result as the following truth table shown...
C !C
F T
T F

Example of not operator


int a = 5, b;
b = !a > 2;
printf("%d %d",a,b);// 5 0 

//(not) have the greater precedence then (>). so first the !a is evaluated and results 0. After than 0>2 is evaluated that is false.


int a = 5, b;
b = !(a > 2);
printf("%d %d",a,b);// 5 0 

Previous Back to C Programming index Next

Comments

Popular posts from this blog

Arrays in C Language

Variable Naming & Scope of Variable

Inline V/S Block Level Element

Variables in Go lang

Identifiers

String in golang

Identify Variable type and values in go lang

Decision Making in Go lang

Installing go lang

Sum of two numbers in go lang