Largest of three numbers using nested ternary operator
A program to demonstrate nesting of ternary operator while finding the largest of three numbers.
Learning Objectives
- Using the nesting of ternary operator to find the largest of three numbers.
Source Code
|
Alternate (?) : |
Run Output
Code Understanding
int a,b,c; cout<<“Enter three integers: “; cin>>a>>b>>c;
Three numbers are collected.
int largest=(a>b)?(a>c?a:c):(b>c?b:c);
Ternary operator nesting is applied to find the largest.
cout<<largest<<” is largest.”<<endl;
Largest number is printed.
Notes
- If all the numbers are same it reports the number. The better way thus could be if-else ladder which can also report if the numbers are not distinct.
- If two of three numbers are same they this logic works fine and the larger one is reported.
Common Errors
- Be careful in putting brackets while using the nesting of ternary operator.
Suggested Filename(s): ter-nest.cpp
sunmitra| Created: 23-Jan-2018 | Updated: 23-Jan-2018|