Conditional Operator in C
Q) Give syntax for the conditional operator.
Q)Give syntax for the conditional operator and explain with a flow chart.
Q)Give syntax for the conditional operator and explain with an example.
|Image Source ~ Crafted With ©Ishwaranand – 2020 ~ Image by ©Ishwaranand|
- The C language has an unusual operator, useful for making a two-way decision. This operator is a combination of ? and : and takes three operands. That operator is commonly known as the conditional operator. It is also known as a ternary operator as it has three operators. It has the following general form.
- Conditional-expression ? expression1 : expression2
- Here, conditional expression, expression1 and expression2 are the expressions.
Working of Condition operators:
- Conditional- expression is evaluated first. If it is true (i.e. non-zero), then expression 1 will be evaluated and returned as the result otherwise expression2 will be evaluated and returned as the result. Note that only one of the expressions (either expression 1 or expression 2) is evaluated.
consider the following piece of code:
x=(a>b) ? a:b;
Here, x will contain a value of b (i.e. 15)
- Note: conditional operator, ternary operator and operator having three operands are the same things.
Q) Write any program to demonstrate the working of the conditional operator.
Q) Write a program to find a larger number from two numbers using a conditional operator.
/* program for finding the largest out of two numbers, using conditional operator */
int a, b, 1;
printf(“Enter two numbers : “)
scant(“%d%d”, &a, &b);
1= (a>b) ? a:b;
printf(“nLargest number is %d”, 1);
Enter two numbers: 10 12
Largest number is 15
Last updated on Sunday - May 21st, 2023