OCJP

Conditional Operator (Ternary Operator) in C Language

There is a special operator ‘?’ (called Conditional or ternary) in C Language that is used like if.

Syntax

var = (condition)? true part : false part ;

Example

#include<stdio.h>
#include<conio.h>
void main()
{
int x,y,max;
clrscr();
printf("\nEnter X :");
scanf("%d",&x);
printf("\nEnter Y :");
scanf("%d",&y);

max = (x>y)?x:y;
//We can replace with if like
// if(x>y)
// max=x;
// else
// max=y;
printf("\nMax Value is %d",max);
getch();
}

Here if x is greater than y then max will be x else max will be y. Another example.

diff= (x>y)?(x-y)?(y-x);

Here what ever values you enter, positive difference will be stored to diff variable.

We can also use nested ternary operator like if we want to detect maximum of three numbers we can use like:

max = (x>y)?(x>z)?x:z : (y>z)?y:z;
/*
if(x>y)
{
if(x>z)
max=x;
else
max=z;
}
else if(y>z)
max=y;
else
max=z;
*/

Leave a Reply

Your email address will not be published. Required fields are marked *


× How can I help you?