Ternary operator in C with syntax and example.

Ternary operator in C with syntax and example.

 The ternary operator in c programming

The ternary operator is also known as a conditional operator. It checks conditions to make decisions. Ternary operator consists of two symbols: Question mark(?) and the colon(:) but not together. The operator is called ternary operator if it has a provision of Question mark(?) and the colon(:) symbol. This is the only operator in the C program that takes three operands so it is called ternary operators.

Syntax of ternary operator

exp1?exp2:exp3

In this operator first, exp1 is evaluated if it is true then a statement along exp2 will be executed otherwise statement along exp3 will be executed.

Example of ternary operator in C

Program to find largest number among two number using ternary operator

#include<stdio.h>

#include<conio.h>

void main()

{

int a, b, max;

printf("\n Enter two digit");

scanf("%d%d",&a,&b);

max=(a>b)?a:b;

printf("\n Largest number=%d",max);

getch();

}

Output


In above example, User have given the values of a and b are 10 and 5 respectively.The statement max=(a>b)?a:b; where condition is evaluate as (a>b) if it is true then max = a otherwise max=b. In this example 10 is largest than 5 so largest number is 10
 

The simple and understandable syntax is 

Variable= (condition check)? (if statement):(else statement)

 

 



Post a Comment

0 Comments