Implementing ternary operator without any conditional statement
Last Updated :
16 Jun, 2022
How to implement ternary operator in C++ without using conditional statements.
In the following condition: a ? b: c
If a is true, b will be executed.
Otherwise, c will be executed.
We can assume a, b and c as values.
1. Using Binary Operator
We can code the equation as :
Result = (!!a)*b + (!a)*c
In above equation, if a is true, the result will be b.
Otherwise, the result will be c.
C++
#include <bits/stdc++.h>
int ternaryOperator( int a, int b, int c)
{
return ((!!a) * b + (!a) * c);
}
int main()
{
int a = 1, b = 10, c = 20;
std::cout << ternaryOperator(a, b, c) << '\n' ;
a = 0;
std::cout << ternaryOperator(a, b, c);
return 0;
}
|
Python 3
def ternaryOperator( a, b, c):
return (( not not a) * b + ( not a) * c)
if __name__ = = "__main__" :
a = 1
b = 10
c = 20
print (ternaryOperator(a, b, c))
a = 0
print (ternaryOperator(a, b, c))
|
PHP
<?php
function ternaryOperator( $a , $b , $c )
{
return ((!! $a ) * $b + (! $a ) * $c );
}
$a = 1;
$b = 10;
$c = 20;
echo ternaryOperator( $a , $b , $c ) , "\n" ;
$a = 0;
echo ternaryOperator( $a , $b , $c );
?>
|
Javascript
<script>
function ternaryOperator(a,b,c)
{
return ((!!a) * b + (!a) * c);
}
let a = 1, b = 10, c = 20;
document.write( ternaryOperator(a, b, c)+ "<br>" );
a = 0;
document.write( ternaryOperator(a, b, c)+ "<br>" );
</script>
|
2. Using Array
int arr[] = { b, a };
We can return the value present at index 0 or 1 depending upon the value of a.
- For a= 1, the expression arr[a] reduces to arr[1] = b.
- For a= 0, the expression arr[a] reduces to arr[0] = c.
C
#include <stdio.h>
int ternary( int a, int b, int c)
{
int arr[] = { c, b };
return arr[a];
}
int main( void )
{
int a = 10, b = 20;
printf ( "%d\n" , ternary(0, a, b));
printf ( "%d\n" , ternary(1, a, b));
return 0;
}
|
C++
#include <iostream>
using namespace std;
int ternary( int a, int b, int c)
{
int arr[] = { c, b };
return arr[a];
}
int main( void )
{
int a = 10, b = 20;
cout<<ternary(0, a, b)<<endl;
cout<<ternary(1, a, b)<<endl;
return 0;
}
|
Python3
def ternaryOperator( a, b, c):
arr = [ c, b ]
return arr[a]
if __name__ = = "__main__" :
a = 1
b = 10
c = 20
print (ternaryOperator(a, b, c))
a = 0
print (ternaryOperator(a, b, c))
|
Asked In : Nvidia
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...