Conditional operators in c

Conditional operator in C

Conditional operator is a ternary operator (? and ::) which is required three expression as operand let us take example its written as –

Testexpression? expression1 : expression2

1. if Testexpression is true(non zero), then only expression1 is evaluted and it becomes print all the values of this conditional expression
2. if Testexpression is false then expression2 is evaluted and it becomes all the values of this conditional expression.

lets us take conditional expression

x>y is evaluated if the value of this condition expression is true then the value of variable x will be value of conditional expression otherwise the value of y becomes the value of conditional expression

Let us take example to understand the concept of conditional operator

let us suppose x=6 and y=10 and now we are using above conditional operator

Result=x>y ? x : y;

Here in the example the first expression x>y is evaluated so here in the x>y condition it is false so the value of y variable becomes to the condition expression and finally its assign to the result variable

so now let us take example of Conditional operator with program

\*program to print the larger number from two numbers*/
# include < stdio.h >
int
main()
{
int x,y,larger;
printf(“Enter first number \n”);
scanf(“%d”,&x);
printf(“Enter second number \n”);
scanf(“%d”,&y);
larger=x>y ? x : y;
printf(“The larger number is %d”,larger);
return 0;
}

Output :

Enter first number 15
Enter Second number 10
The larger number is 15