Ads

Conditional Operator


CONDITIONAL OPERATOR:

- Conditional operator is ternary operator i.e. it operates on three operands.

Syntax:
<conditional_expression>?<statement1>:<statement2>

- Angle brackets are used for demonstration purpose only and should not be used in your c program.

- If conditional expression is true then statement1 is executed and if false statement2 is executed.

- Conditional operators can be used in the situations like below

5>7?printf("5 is greater"):printf("7 is greater");
x>y?printf("%d is greater",x):printf("%d is greater",y);


Program:

/* A program to find greatest of two numbers */

#include<stdio.h>
int main()
{

 int x,y;
 printf("\n Enter value x:\t");
 scanf("%d",&x);
 printf("\n Enter value y:\t");
 scanf("%d",&y);
 x>y?printf("%d is greater\n",x):printf("%d is greater\n",y);

 return 0;
}



Output:

Enter value x:  56
Enter value y:  78
78 is greater


Program:

/* Write a program to find out if a number is divisible by 2 or not */

#include<stdio.h>
int main()
{
 int x;
 printf("\nEnter value x:\t");
 scanf("%d",&x);
 (x%2)?printf("%d is not divisible by 2\n",x):printf("%d is divisible by 2\n",x);
 return 0;
}



Output:

Enter value x:  5
5 is not divisible by 2



No comments:

Post a Comment