Ternary operator within cout chain for selective printing – CSKC
Sign In

Search

Solved Problem #CPP#2791    siteicon   siteicon  

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

TC++ #2791

 

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

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



Share

Created: 19-Jan-2018 01:35 | Updated: 5-Dec-2018 19:30|