Ads

Comparison or Relational

TRUE or FALSE in C Language: In C language any value other than ’0’ is considered as true and value '0' is considered as false.

COMPARISON/RELATIONAL OPERATOR:

- Greater than, greater than or equal to, less than, less than or equal to, equal to, not equal to are denoted by >, >=, <, <=, ==, != respectively and are called Relational operators.

- These operators return boolean value (true or false) i.e. 1 or 0 after the operation is performed.

Syntax:
<operand> <operator> <operand>;
- Angled brackets are used for demonstration purpose only and should not be used in your c program

Examples:
1) if a=5,b=6
then,
a>b  =>  5>6   returns 0
a>b  =>  5>=6  returns 0
a<b  =>  5<6   returns 1

2) if a=5, b=5
then
a!=b => 5!=5 is false so returns 0
a==b => 5==5 is true so returns 1

- Wondered how to collect the returned value? It’s simple and it is shown below.

x=a>b;
printf("%d",x);/* it will  print value returned by a>b;*/


- we can also write the program as shown below.

printf("%d",a>b);/* it will directly print the returned value */


- Comparison and Relational operators can be used on constants, variables & expressions.

  Example:
Constants:
2<5;
7.3<8.6;
(4/2)==2;
5>=4.9;


Variables:
x>=y;
x!=0;
y==x;

Expressions:
((x+y+z)>5);
(x+2)==y;
x%2==0;


Program:


/*Write a program to find greatest of two numbers using relational operators.*/

#include<stdio.h>
int main()
{
 int x,y;
 printf("\n Enter x=");
 scanf("%d",&x);
 printf("\n Enter y=");
 scanf("%d",&y);
 if(x>y)
 printf("\n x is greater");
 else
 printf("\n y is greater");

 return 0; 
} 

Output:

Enter x=4
Enter y=5
y is greater

NOTE: Here in  above example we used if keyword, we will know more about it in control statements chapter, but for now, if() is a non-iterative conditional control statement used to decide which block of statements to execute depending on the condition in parenthesis.


Program:


/* Program using all the relational operators */

#include <stdio.h>
int main()
{
 int a,b;
 printf("\nEnter value of a:");
 scanf("%d",&a);
 printf("\nEnter value of b:");
 scanf("%d",&b);
 printf("a>b = %d\n", a>b);
 printf("a>=b = %d\n",a>=b);
 printf("a<b = %d\n", a<b);
 printf("a<=b = %d\n", a<=b);
 printf("a!=b = %d\n", a!=b);
 printf("a==b = %d\n", a==b);

 return 0;
} 


Output:

Enter value of a:4
Enter value of b:5
a>b = 0
a>=b = 0
a<b = 1
a<=b = 1
a!=b = 1
a==b = 0



No comments:

Post a Comment