send me the code to use of ternary operator
Please explain that how to use ternary operator with code?
Syntax of ternary operator is −
(expression-1) ? expression-2 : expression-3
This operator returns one of two values depending on the result of an expression. If “expression-1” is evaluated to Boolean true, then expression-2 is evaluated and its value is returned as a final result otherwise expression-3 is evaluated and its value is returned as a final result.
Example
Let us write a program to find maximum of two numbers using ternary operator.
#include <iostream>
using namespace std;
int main() {
int a = 10;
int b = 20;
int max = a > b ? a : b;
cout << "Maximum value = " << max << "\n";
return 0;
}
If we compare syntax of ternary operator with above example, then −
- expression-1 is (a > b)
- expression-2 is a
- expression-3 is b
First, expression a > b is evaluated, which evaluates to Boolean false as value of variable ‘a’ is smaller than value of variable ‘b’. Hence value of variable ‘b’ i.e. ‘20’ is returned which becomes final result and gets assigned to variable ‘max’.
Output
When you compile and execute above code it will generate following output −
Maximum value = 20
i hope this helps
if yes hit a like and don’t forgot to mark doubt as resolved
if you have more doubts regarding this feel free to ask