Conditional (Ternary) Operator

  • It needs three operands to perform the task. You can say it an expression also.
  • Syntax : EXP1?EXP2: EXP3;
  • If the EXP1’s result is true then the output is EXP2, or EXP1’s result is wrong the output is EXP3.

We will try to understand it using one example :

main()

{

int i = 10, j = 15 , k ;

k = i<j?100:200;

printf(“i = %d j = %d k = %d\n”,i,j,k);

}

Answer : i = 10 , j =20 , k = 100

  • Program to find highest among two numbers.

#include<stdio.h>

#include<conio.h>

main()

{

int i = 100, j = 20 , k ;

i > j?printf(“i is greater”):printf(“j is greater”);

}

Answer : i is greater.

  • Program to find out highest among three numbers.

#include<stdio.h>

#include<conio.h>

main()

{

int i = 100, j = 20 , k = 30 ;

i > j ? i > k ? printf(“i is greater”) : printf(“k is greater”) : j > k ? printf(“j is greater”) : printf(“k is greater”);

}

Answer : i is greater.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: