Detailed Print – CSKC
Sign In

Search

siteicon
Code Learning#CPP#2943 Back

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

		 

Click to open popup
Alternate (?) : 2946

Run Output

Enter three integers: 1 2 3
3 is largest.

-OR-
Enter three integers: 43 12 32
43 is largest.

-OR-
Enter three integers: 103 104 101
104 is largest.

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