Write a program to use the conditional operator with two values.

conditional operator
#include<stdio.h>
#include<conio.h>
main()
{
	printf("Result =%d",4==2*2 ? 4 : 5);
	getch();
}



/*Conditional Operator(?);-
The conditional Operator is also called the ternary operator.
if the codition is true, the first statement is executed oterwise the second statement executed.
Syntax of conditional operator is:-
Condition     ?       (expressional 1)       :     (expressional 2)  
Above program, the condition 2==3 is false.Hence 5 is printed.
*/ 

The program demonstrates the use of the conditional operator “?” in C. The conditional operator is a shorthand way of writing an if-else statement in a single line. The syntax for the conditional operator is as follows:

condition ? expression1 : expression2

The condition part is evaluated, and if it is true, the expression to the left of the : (expression1) is evaluated, and if it is false, the expression to the right of the : (expression2) is evaluated. The result of the evaluated expression is returned by the conditional operator.

In the given program, the condition 4 == 2 * 2 is evaluated, which is true. Hence, the expression 4 to the left of the : is evaluated and the value 4 is printed.

In other words, the program is equivalent to the following code:

if (4 == 2 * 2) {
    printf("Result =%d", 4);
} else {
    printf("Result =%d", 5);
}

The conditional operator is useful when you want to write a simple if-else statement in a single line, as it provides a compact way of writing the if-else statement.

Thanks

Write a program to use the conditional operator with two values.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top