Ternary Operator ( ? : ) in C++
The conditional operator is also known as a ternary operator. It is used to write conditional operations provided by C++. The ‘?’ operator first checks the given condition, if the condition is true then the first expression is executed otherwise the second expression is executed. It is an alternative to an if-else condition in C++.
Syntax of Ternary Operator in C++
condition ? expression1 : expression2
Flowchart of Conditional Operator in C++
Example of Ternary Operator in C++
The below program demonstrates the use of a conditional operator to find the maximum of two numbers.
C++
// C++ program to demonstrate the use of ternary/conditional // operator to find the max from two numbers #include <iostream> using namespace std; int main() { int num1 = 10, num2 = 40; int max; // if the condition is true then num1 will be printed // else num2 will printed max = (num1 > num2) ? num1 : num2; cout << max; return 0; } |
40
Decision Making in C++
Decision-making in C++ involves the usage of conditional statements (also called decision control statements) to execute specific blocks of code primarily based on given situations and their results.
So basically, in decision-making, we evaluate the conditions and make a decision about which part of the code should be executed or not. It allows selective code execution which is crucial for controlling the flow of a program and making it more dynamic.