# C Language: Conditional Operator (? :) Tutorial | Ternary Operator/ Conditional operator tutorial with Examples

Spread the love

### Conditional Operator ( ? and : )

** Conditional operator is a ternary operator.** Ternary operator means it requires three operands.

i.e Left side expression, Middle Expression, Right side Expression.

This is written as.

**Value = Expression 1 ? Expression 2 : Expression 3 ;**

### How Conditional Operator Works :

Firstly Expression 1 is evaluated,

**if Expression 1 is true or non zero then the return value is Middle Expression that is Expression 2. If the Expression 1 is false or Zero then return value is Expression 2 i.e Right side Expression.**

__Example :__**Max = X < Y ? Y : X ;**

Here first the expression X < Y is evaluated, if the value of expression is true then the Max is X.otherwise the value of Y becomes the value of Conditional Expression.

Suppose X = 10 and Y = 20 then above condition is

**Max = 10 < 20 ? 20 : 10 ;**

First expression 10< 20 is evaluated, since it is true value 20 becomes the value of Max.

let’s take one more example

**a = 5 > 8 : 20 : 30 ;**

first 5 > 8 is evaluated since it is false value of a (variable a) is 30.

### Quick Notes about Conditional Operator :

**Number of Question marks(?) and Colons(:) should be Equal.**

Ex 1: a = 10 ? 20 : 30 ;

number of question marks and colons are equal. and value of a is 20 because 10(test Expression) is non-zero.

Ex 2: a = 2 > 5 ?10 : 20 : 30 ;

Error : number of Question marks and Colons are not equal.

**Every Colon should be Followed by Question mark.**

Ex : a = 10 < 15 ? 1 : 20 : 5 ? 30 ;

Error : Second colon is not followed by Question mark.

### Program : Understanding Conditional operator with Example Program :

__Program to calculate Minimum Value among three Numbers :__-
**#include <stdio.h>** -
**int main(void) {** -
**int x,y,z,min;** -
**x = 10;** -
**y = 20;** -
**z = 5 ;** -
**min = (x<y && x<z) ? (x) : (y<z) ? (y) : (z) ;** -
**printf(“Minimum Value is : %d n“,min);** -
**return 0;** -
**}**

__Output :__Minimum Value is : 5

#### Related Tutorials :

**Arithmetic Operators with Examples.****Arithmetic operators priority and it’s Associativity.****Modulus Operator and Hidden Concepts of Modulus Operator.****Precedence Table or Operators Priority Table.****Assignment Operator, Usage, Examples****Increment Operator and Different types of Increment operators Usage with Examples.****Decrement Operator and Different types of Decrement operators with Examples.****Logical or Boolean Operators.**

## 1 Response

[…] Conditional Operator. […]