Conditional Operators [ ?: ] are also called as Ternary Operator .
int main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
if(num%2==0)
printf("\nNumber is Even");
else
printf("\nNumber is Odd");
}
We can write this program as –
#include<stdio.h>
int main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("\nNumber is Even"):printf("\nNumber is Odd");
}
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
Explanation:
- Expression1 is a Boolean Condition i.e it results into either TRUE or FALSE
- If result of expression1 is TRUE then expression2 is Executed.
- Expression1 is said to be TRUE if its result is NON-ZERO.
- If result of expression1 is FALSE then expression3 is Executed.
- Expression1 is said to be FALSE if its result is ZERO.
Example : Check whether Number is Odd or Even
#include<stdio.h>int main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
if(num%2==0)
printf("\nNumber is Even");
else
printf("\nNumber is Odd");
}
We can write this program as –
#include<stdio.h>
int main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("\nNumber is Even"):printf("\nNumber is Odd");
}
Note :
Operator that works on 3 operands is called as tertiary operator.
No comments:
Post a Comment