Ternary / Conditional Operator
Welcome to CodingFizz,
In this tutorial, We will what is the ternary operator, and how it is used in programming languages.
The ternary operator is known as the conditional operator. It is similar to the If-else statement. It takes less space and helps to write decision-making statements in the shortest way. It works the same in all languages.
Syntax:
Variable = Expression1 ? Expression2: Expression3
Working of Ternary Operator:
Examples Of Ternary Operator:
The Example of the ternary operator in C++ language. In this example find the largest number between two numbers.
// Find The Largest Number Between Two Numbers.
#include <iostream>
using namespace std;
int main()
{
int n1 = 6, n2 = 19, lar;
lar = (n1 > n2) ? n1 : n2;
cout << "Largest Number is " <<lar;
return 0;
}
Output:
Largest Number is 19
// Find The Largest Number Between Three Numbers.
#include <iostream>
using namespace std;
int main()
{
int n1 = 10, n2 = 25, n3 = 15, lar;
lar = (n1 > n2) ? (n1 > n3 ? n1 : n3) : (n2 > n3 ? n2 : n3);
cout << "Largest number is " <<lar;
return 0;
}
Output:
Largest Number is 25
0 Comments