Ternary Operator in C++

Advertisements

First Program in C++ Expression Evaluation 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

Ternary Operator

Advantage of Ternary Operator

Using Ternary Operator 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 ? cout<<"a is less" : cout<<"a is greater";

Flow Diagram

Ternary Operator

Find largest number among 3 numbers using ternary operator

Example Ternary Operator in C++

#include<iostream.h>
#include<conio.h>

void main()
{
int a, b, c, large;
clrscr();
cout<<"Enter any three number: ";
cin>>a>>b>>c;
large=a>b ? (a>c?a:c) : (b>c?b:c);
cout<<"Largest Number is: "<<large;
getch();
}

Output

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

First Program in C++ Expression Evaluation in C++

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements