-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathternaryOperator.cpp
More file actions
39 lines (32 loc) · 990 Bytes
/
ternaryOperator.cpp
File metadata and controls
39 lines (32 loc) · 990 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
// Using ternary operator
std::cout << "Ternary operator result: ";
std::cout << (number > 0 ? "Positive" : (number < 0 ? "Negative" : "Zero")) << std::endl;
// Equivalent if-else statement
std::cout << "If-else result: ";
if (number > 0) {
std::cout << "Positive";
} else if (number < 0) {
std::cout << "Negative";
} else {
std::cout << "Zero";
}
std::cout << std::endl;
// Another example with ternary operator
int age = 18;
std::string status = (age >= 18) ? "Adult" : "Minor";
std::cout << "Age " << age << " is " << status << std::endl;
// Equivalent if-else
std::string status2;
if (age >= 18) {
status2 = "Adult";
} else {
status2 = "Minor";
}
std::cout << "Age " << age << " is " << status2 << std::endl;
return 0;
}