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 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
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
No comments:
Post a Comment
Hai , Post your comment . (required, Bugs, Errors )