Exercise 3-14 (The ternary operator, IfThen)
Chapter_3 Exercise_3-13 | Comma Exercise_3-15 |
Exercise 3-14 TCP1, p. 228
Exercise 3-14. Modify Ifthen.cpp (Section ch3-Controlling_Execution) to use the ternary if-else operator (?:).
Ternary.cpp download
// Demonstration of ternary operator
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
int i;
cout << "Type a number and 'Enter'" << endl;
cin >> i;
(i > 5) ? cout << "It's greater than 5" << endl
: // i <= 5
(i < 5) ? cout << "It's less than 5" << endl
: cout << "It's equal to 5" << endl;
// More formal:
(i > 5) ? cout << "It's greater than 5" << endl
: // i <= 5
(
(i < 5) ? cout << "It's less than 5" << endl
: cout << "It's equal to 5" << endl
);
cout << "Type a number and 'Enter'" << endl;
cin >> i;
(i < 10) ?
(
(i > 5) ? cout << "5 < " << i << " < 10" << endl
: cout << i << " <= 5" << endl
)
: cout << i << " >= 10" << endl;
return 0;
}
/*
g++ Ternary.cpp -o Ternary
./Ternary
Type a number and 'Enter'
1
It's less than 5
It's less than 5
Type a number and 'Enter'
2
2 <= 5
./Ternary
Type a number and 'Enter'
5
It's equal to 5
It's equal to 5
Type a number and 'Enter'
6
5 < 6 < 10
./Ternary
Type a number and 'Enter'
7
It's greater than 5
It's greater than 5
Type a number and 'Enter'
10
10 >= 10
*/
Note: See also ch2-items and Exercise_2-10 on the blog Kernighan_and_Ritchie, Chapter_2, Sec. 2.11.
Chapter_3 Exercise_3-13 | BACK_TO_TOP | Comma Exercise_3-15 |
Comments
Post a Comment