C++ 09: Ternary Operators
A ternary operator evaluates the test condition and executes a block of code based on the result of the condition.
Its syntax is
condition ? expression1 : expression2;1. WAP to find greatest of three using ternary operator
#include <iostream>
using namespace std;main(){ int a,b; int x;
cout<<"Enter two numbers: "; cin>>a>>b;
x= (a>b)?a:b;
cout<<"Greatest is "<<x; return 0;}Output
Enter two numbers: 2 3 Greatest is 3 2)WAP to check greatest of two using Ternary Operators
#include <iostream>
using namespace std;main(){ int p;
cout << "Enter a number : "; cin >> p;
(p % 2 == 0) ? cout << "Even Number" : cout << "Odd Number";
return 0;}Output
Enter a number:44
Even Number3)WAP to read three numbers and and find greatest of three numbers using ternary op
#include <iostream>
using namespace std;main(){ int x,y, z; int m, n, g;
cout << "Enter three numbers: "; cin >> x >> y >> z;
g = (m = (x > y) ? x : y) > (n = (z > y) ? z : y) ? m : n;
cout << "Greatest is " << g; return 0;}Enter three numbers:2 6 4
Greatest is 6
Comments
Post a Comment