Practice
Resources
Contests
Online IDE
New
Free Mock
Events New Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
Events
Attend free live masterclass hosted by top tech professionals
New
Scaler
Explore Offerings by SCALER

# Conditional or Ternary Expression

There are expressions of a special kind, the conditional expressions, these are not statements, but they are one sort of contraction of the `if-then` construct.

This kind of expression can help to produce highly readable assignment statements fitting onto one line of the source code.

Syntax:

`( condition ) ? expressionIfTrue : expressionIfFalse;`

First the condition is evaluated and the side effects of this evaluation carry out their impact on the local environment.

• If the result is true then only the `expressionIfTrue` is evaluated (causing side effects) and this second result is the value of the whole conditional expression, and the `expressionIfFalse` is not evaluated (and hence cause no side effects).
• If the condition evaluates to false, then the situation is converse, the resulting values is given by the evaluation of the false branch of the conditional expression, and the true branch is not evaluated.

A common use of the conditional expression is to assign the value `x` or `y` to `a`, depending on an easily decidable condition, say `x>y`.

Example:

`int x = 7;int y = 5;int a = ( x > y ) ? x : y; // here we are using conditional expression to evaluatecout << a << endl;// The above conditional expression is equivalent to/*if (x > y){      // here we are usig if-else which will gave same output    a = x;    cout << a << endl;}else {    a = y;    cout << a << endl;}*/`

Try the following example in the editor below.

Given two integer `x` and `y`, using Conditional or Ternary expression, print “Robin” if the value of x is less than or equal to y else print “Rahul” (without quotes).

Sample Input:

`x = 10y = 9`

Sample Output:

`Rahul`

Hints
• Complete Solution

## Discussion

Free Mock Assessment
Fill up the details for personalised experience.
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
*Enter the expected year of graduation if you're student
Current Employer
Company Name
College/University Name
Job Title
Job Title
Software Development Engineer (Backend)
Software Development Engineer (Frontend)
Software Development Engineer (Full Stack)
Data Scientist
Android Engineer
iOS Engineer
Devops Engineer
Support Engineer
Research Engineer
Engineering Intern
QA Engineer
Co-founder
SDET
Product Manager
Product Designer
Backend Architect
Program Manager
Release Engineer
Data Analyst
Data Engineer
Non Coder
Other
Edit
Resend OTP
By clicking on Start Test, I agree to be contacted by Scaler in the future.