Create a free account on Computer Sir Ki Class and unlock access to valuable learning resources.
Exam Paper Downloads: After registering and logging in, you can download exam question papers in PDF format to practice and prepare for your exams.
Student Support: Get assistance with your doubts, queries, and questions related to your studies. Our support is here to help you understand topics and resolve your learning difficulties.
Register today and make your exam preparation easier and more effective!
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
Run Output
YES
NO
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.