Problem Statement - Ternary operator within cout chain for selective printing
Initialise a character variable. Now using the ternary operator within the cout chain of printing, print YES if initialised variable is Y and print NO if it is anything else.
Learning Objectives
- Learning to use ternary operator within the cout chain.
Solution
Run Output
Solved Problem Understanding
char c=’Y’; //Character variable initialised with Y
cout<<((c==’Y’)?”YES”:”NO”)<<endl;
Here with in cout chain we use the ternary operator as – First operand is check condition if the c==’Y’. Second operand – String literal “YES“, Third Operand – String Literal “NO“. This will print YES as first condition is true. The whole expression should be in a round brace pair as it is inside the cout chain.
c=’x’; Initialised with value other than Y.
cout<<((c==’Y’)?”YES”:”NO”)<<endl;
No is printed using the ternary operator within the cout chain.
Notes
- Ternary operator provides a simple selective printing of string literals or variable values. As against if-else construct this method is quite efficient without the use of intermediate variables.
Common Errors
- Student must watch out for proper use of round braces around expressions while using such a syntax.
Suggested Filename(s): terncout.cpp
