🧮 Find Maximum and Minimum Using Ternary Operator in C++
The ternary operator in C++ offers a concise way to make decisions based on conditions. It can be used to find the maximum or minimum between two numbers in just one line of code, making your programs shorter and cleaner.
💡 How the Ternary Operator Works
The ternary operator is written as:
condition ? expression_if_true : expression_if_false;
To find the maximum:
max = (a > b) ? a : b;
To find the minimum:
min = (a < b) ? a : b;
📄 C++ Code Example
#include <iostream>
using namespace std;
int main() {
int num1, num2;
int maximum, minimum;
// Input from user
cout << "Enter the first number: ";
cin >> num1;
cout << "Enter the second number: ";
cin >> num2;
// Find maximum and minimum using ternary operator
maximum = (num1 > num2) ? num1 : num2;
minimum = (num1 < num2) ? num1 : num2;
// Display results
cout << "Maximum: " << maximum << endl;
cout << "Minimum: " << minimum << endl;
return 0;
}
✅ Sample Output
Enter the first number: 12 Enter the second number: 8 Maximum: 12 Minimum: 8
📘 Definition: Using Ternary Operator to Find Max and Min
The ternary operator in C++ is a shorthand conditional expression that evaluates a condition and returns one of two values based on whether the condition is true or false. It is commonly used for simple comparisons, such as finding the maximum or minimum of two numbers. This method enhances code readability and reduces the number of lines in your program.
Using the ternary operator is efficient and preferred for basic conditional assignments in performance-critical or minimalistic code environments.
🧠 Final Thoughts
Mastering the ternary operator is essential for writing clean and efficient C++ programs.
It's a perfect tool for simplifying decision-making logic, especially in scenarios where a full if-else
block may be too verbose.
Post a Comment