Conditional Operator (OR) Ternary Operator - C-Tutorial

Latest

Wednesday, 16 November 2016

Conditional Operator (OR) Ternary Operator

Conditional Operator

C language supports a ternary operator pair ? : as conditional operator.  Any expression that forms with the combination of conditional operator pair and operands is termed as a conditional expression.

The general format of conditional operator pair is:

Syntax: (Expression1) ? Expression2 : Expression3 

Here,

  • First Expression1 is evaluated.  It produces either TRUE of FALSE.
  • If Expression1 outcome is TRUE, then Expression2 is evaluated and becomes result of the total expression.
  • If Expression1 outcome is FALSE, then Expression3 is evaluated and becomes result of the total expression.

i.e., either Expression2 or Expression3 is evaluated depending upon the outcome of Expression1.

/* TO FIND MAX VALUE USING CONDITIONAL OPERATOR */

#include<stdio.h>
#include<conio.h>

main()
{
int a,b,max;
clrscr();
printf("\nEnter Two Numbers:");
scanf("%d%d",&a,&b);
max=(a>b)?a:b;
printf("\nMaximum Number:%d",max);
getch();
}


/* TO FIND MAX VALUE USING CONDITIONAL OPERATOR */

#include<stdio.h>
#include<conio.h>

void main()
{
int a,b,c,max;
clrscr();
printf("\n Enter three integer value: ");
scanf("%d%d%d",&a,&b,&c);
max=a>b?(a>c?a:c):(b>c?b:c);
printf("\n Max value is: %d",max);
getch();
}

No comments:

Post a Comment