Conditional operator in C | Ternary Operator in C

Preview

Conditional operator in C

Conditional operator is also known as ternary operator.

This operator is known as ternary operator because it has three operands.

Ternary operator is represented as ?: .

It is used to check a condition and depending upon the condition, particular instruction is executed by the compiler.

Syntax:

Condition? Block1: Block2;

Condition is any relational or logical expression. Which will be checked to see which block of statements should be executed.

Block1 refers to C language statement which will be executed if condition is true.

Block2 refers to C language statement which will be executed if condition is false.


Example 1

Program to demonstrate the use of conditional operator
#include<stdio.h>
int main()
{
int a=15,b=5,c;
c=a>b?a:b;
printf(“\nc=%d”,c);
return (0);
}
Output
c=15

Description

In the above program, expression c=a>b?a:b is evaluated.

Variable a contains 15 and b contains 5

Condition a>b is true, so statement after question mark (?) will be evaluated and c will contain value of a i.e. 15.

Example 2

Program to find largest among two numbers using conditional operator.

#include<stdio.h>
int main()
{
int a,b,c;
printf(“\nEnter value of a=”);
scanf(“%d”,&a);
printf(“\nEnter value of b=”);
scanf(“%d”,&b);
c=a>b?a:b;
printf(“\nLargest value=%d”,c);
return(0);
}
Output
Enter value of a=9
Enter value of b=14
Largest value= 14

Example 3

 Program to read percentage of a student. If percentage is more than 35 then PASS should be displayed otherwise FAIL should be displayed.
#include<stdio.h>
int main()
{
float percentage;
printf(“\nEnter percentage=”);
scanf(“%f”,&percentage);
percentage>35?printf(“PASS”): printf(“FAIL”);
return(0);
}
Output
Enter percentage=95
PASS



 

Lesson tags: conditional operator of c, operator to apply conditions in c, ternary operator of c
Back to: C Programming Language