Saturday, 15 December 2018

Ternary Operator in C


Ternary Operator in C

If any operator is used on three operands or variable is known as Ternary Operator. It can be represented with ? : . It is also called as conditional operator

 

Advantage of Ternary Operator

Using ?: reduce the number of line codes and improve the performance of application.

Syntax

expression-1 ? expression-2 : expression-3
In the above symbol expression-1 is condition and expression-2 and expression-3 will be either value or variable or statement or any mathematical expression. If condition will be true expression-2 will be execute otherwise expression-3 will be executed.

Syntax

a<b ? printf("a is less") : printf("a is greater");

Flow Diagram





































Find largest number among 3 numbers using ternary operator

Example

#include<stdio.h>
#include<conio.h>
 
void main()
{
int a, b, c, large;
clrscr();
printf("Enter any three number: ");
scanf("%d%d%d",&a,&b,&c);
large=a>b ? (a>c?a:c) : (b>c?b:c);
printf("Largest Number is: %d",large);
getch();
}

Output

Enter any three number: 5 7 2
Largest number is 7


No comments:

Post a Comment