C conditional operators



Conditional Operators [ ?: ] : Ternary Operator Statement in C

  1. They are also called as Ternary Operator .
  2. They also called as ?: operator
  3. Ternary Operators takes on 3 Arguments

Syntax :

expression 1 ? expression 2 : expression 3

where

  • expression1 is Condition
  • expression2 is Statement Followed if Condition is True
  • expression2 is Statement Followed if Condition is False
Conditional Statement in C Programming Lanuage - Ternary Operator

Conditional Statement in C Programming Lanuage

Meaning of Syntax :

  1. Expression1 is nothing but Boolean Condition i.e it results into either TRUE or FALSE
  2. If result of expression1 is TRUE then expression2 is Executed
  3. Expression1 is said to be TRUE if its result is NON-ZERO
  4. If result of expression1 is FALSE then expression3 is Executed
  5. Expression1 is said to be FALSE if its result is ZERO

Live Example : Check whether Number is Odd or Even

#include<stdio.h>

int main()
{
int num;

printf("Enter the Number : ");
scanf("%d",&num);

flag = ((num%2==0)?1:0);

if(flag==0)
   printf("\nEven");
else
   printf("\nOdd");
}

More Simply we can write this program as –

#include<stdio.h>

int main()
{
int num;

printf("Enter the Number : ");
scanf("%d",&num);

(num%2==0)?printf("Even"):printf("Odd");

}

Big Note : Ternary Operator

Operator that works on 3 operands is called as tertiary operator. Ternary operator . Read rules of using Ternary Operator in C . [Wiki Article : http://en.wikipedia.org/wiki/Ternary_operation ]