Conditional Operator in C- Free C programming tutorial

In this tutorial you will be familiarize with the conditional operator ( ?: ) available in C programming language.

 CONDITIONAL OPERATOR (?:) IN C programming language :

  • Conditional operator available in C programming language is defined as the operator which checks condition that is written before (?) and returns one value as a result or output based on the checking.
  • This operator is one and the same as if-else conditional statements.
  • If condition is true then it will returns first value but when condition is false it will returns another value.
  • It is also termed as ternary operator.

Conditional operator’s symbol is given as :
(?:)

Syntax of the conditional or ternary operator is given below :

(test_conditional_expression)? Expression_1: Expression_2 ;

The conditional operator works as follows:

  • The first expression test_conditional_expression is evaluated first. Then  this expression evaluates to 1 if condition is true and evaluates to 0 if condition is falsefalse.
  • If test_conditional_expression is true,Expression_1 is evaluated.
  • If test_conditional_expression is false, Expression-2 is evaluated.

For example :

(A > 100  ?  0  :  1);

In above example, if value stored in variable A is greater than 100, then 0 is returned else 1 is returned as output.
This is equivalent to if else conditional statements.

If  conditional operators return a value then we have to store the output i.e. returned value in a variable.
Then,
the syntax is given below:

Data_type Variable_name = (test_conditional_expression)? Expression1: Expression2 ;

For example:

int x =    (A > 100  ?  0  :  1);

In above example, if value stored in variable A is greater than 100, then 0 is returned else 1 is returned as output and returned value is stored in variable x.

EXAMPLE of PROGRAM which ILLUSTRATES CONDITIONAL/TERNARY OPERATOR in C:

Code to check whether the number entered by user is an even number or an odd number:

// Header file which contains functions for standard input and output manipulative operation.
#include <stdio.h>   
 
int main()  // Compiling of code start from main function
{
    int x ;  // Declaration of local variable

// To display on console screen
   printf(“Enter a value…… /n ”);

// To get input from user
   scanf(“%d”,&x);

// Use of conditional operator 
// to check whether the number entered by user is an even or an odd number.
   ( x % 2 == 0) ?  printf(“Entered number is an even number.”) : printf(“Entered number is an odd number.”);

}

if entered value is 50 then
OUTPUT:

Enter a value……50
Entered number is an even number.

But,
if entered value is 45 then
OUTPUT:

Enter a value……45
Entered number is an odd number.

This is all about conditional/ternary operator available in C language .If you have any query please comment below.

Leave a Comment

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