C Conditional Operator Statement

by Gautam Sethi
336 views

It is similar to the if-else statement. The if-else statement takes more than one line of the statements, but the conditional operator finishes the same task in a single statement. The conditional operator in C is also called the ternary operator because it operates on three operands.

Syntax:-

expression1 ? expression2 : expression3;

or for simplicity, we write it as

condition ? true statement : false statement;
Code language: JavaScript (javascript)

The expression1 is evaluated, it is treated as a logical condition. If the result is non-zero then expression2 will be evaluated otherwise expression3 will be evaluated. The value after evaluation of expression2 or expression3 is the final result.

The conditional operator in C works similar to the conditional control statement if-else. Hence every code written using conditional operator can also be written using if-else. When compared with if-else, conditional operator performance is high.

if(expression1) { expression2; } else { expression3; }
Code language: JavaScript (javascript)

EXAMPLE

Find maximum in the given two numbers using the conditional operator in C

#include<stdio.h> int main() { float num1, num2, max; printf("Enter two numbers: "); scanf("%f %f", &num1, &num2); max = (num1 > num2) ? num1 : num2; printf("Maximum of %.2f and %.2f = %.2f", num1, num2, max); return 0; }
Code language: C/AL (cal)

Output

Enter two numbers: 12.5 10.5
Maximum of 12.50 and 10.50 = 12.50

First the expression, (num1 > num2) is evaluated. Here num1=12.5 and num2=10.5; so expression (num1>num2) becomes true. Hence num1 is the maximum number, and it is assigned to the variable max.

More than one conditional operator in a statement

We can use more than one conditional operator in a statement. But in this case, it makes harder to understand the code. Use the ternary operator only when the resulting statement is short. This will make your code concise and much more readable.

value = (exp1)?1:(exp2)?2:(exp3)?3:0;

EXAMPLE

Largest among three numbers using the conditional operator

Program to find the maximum of three numbers using conditional operators.

#include<stdio.h> int main() { float a, b, c, max; printf("Enter three numbers: "); scanf("%f %f %f",&a, &b, &c); max = (a>b && a>b)? a: (b>a && b>c)? b:c; printf("Maximum number = %.2f",max); return 0; }
Code language: C/AL (cal)

Output:-

Enter three numbers: 10 30 12
Maximum number = 30.00

If you enjoyed this post on Conditional Operator , share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

You may also like