Search This Blog

Conditional Operator in C and C++

Conditional Operator is an operator which is substitutive for if-else statements. It is a ternary operator (operator which operates on 3 operands). It is often called ?: operator. The operands are expression1, expression2 and expression3. The syntax is as follows:

expression1 ? expression2 : expression3

The expression expression1  will be evaluated always. Execution of expression2 and expression3 depends on the outcome of expression1. expression1 is checked whether true or not. It is considered like a boolean variable. The outcome of an expression is true if it has a non zero value. If its value is zero, the outcome of expression is false. If the expression1 is true, then expression2 is evaluated. If the expression1 is false, then expression3 is evaluated. Consider the following example:



int t=(a>b)?a:b;

In the above assignment statement,if the value of variable a is greater than that of variable b, the outcome of expression a>b is non zero (true) and second expression will be evaluated. Therefore, a will be stored in t. If the value of variable a is less than that of variable b, the outcome of expression a>b is zero (false) and third expression will be evaluated. Therefore, b will be stored in t.



The test expression expression1 can be any expression like a>b, a==b, a!=b etc. It is also possible that expression2 and/or expression3 are variables  or expressions. A nesting of conditional operator is possible while any of the two expressions expression2 and expression3 is an expression with conditional operator. They can be printf statements also.

Simple Example programs:


1) Finding largest of two numbers:


#include<stdio.h>
main()
{
int a,b,c;
printf("Enter two numbers");
scanf("%i%i",&a,&b);
c=(a>b)?a:b;
printf("largest=%d",c);
}
 

2) Checking odd or even:

#include<stdio.h>
main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("Even"):printf("Odd");
// using printf statements in conditional operator.
}

3) Finding largest of three numbers:


Using conditional operator inside  conditional operator (nesting)

#include<stdio.h>
main()
{
int a,b,c,d;
printf("Enter three numbers");
scanf("%i%i%i",&a,&b,&c);
d=(a>b)?((a>c)?a:c):((b>c)?b:c);
printf("largest=%i",d);
}

No comments: