Conditional Operator in C


Conditional Operator

 

Conditional Operator an important statement is used to make two-way decisions in the programming language C.

It is also called the ternary operator because it is based on three operands i.e., three operands are required to use it.

To write it question mark (?) and colon (:) symbols are used. It is known as a conditional operator and its general syntax is as follows –

 

Conditional expression ? exp1 : exp 2;

 

This operator is also used in place of the normal if statement. In fact, it is more efficient than if statement and reduces program code but is used only for two-way conditions.

For example –

 

conditional operator

 

Both the above codes give the same output.

 

Understand with examples

 

// C program to find smallest among two numbers using ternary operator

 

#include < stdio.h >

int main()

{

    int m = 4, n = 5;

   (m < n) ? printf("m is smaller than n that is %d > %d", m, n) : printf("n is smaller than m that is %d > %d",n, m);

    return 0;

}

 

Output

m is smaller than n that is 5 > 4

 

// C program to Find the number is positive or negative using the conditional operator.

 

#include < stdio.h >

int main()

{

  int num;

  printf("Enter a number: ");

  scanf("%d", &num);

  (num>=0) ? printf("+ve") : printf("-ve");

  return 0;

}

 

Output

Enter a number: 9

+ve. 

Enter a number: -5

-ve.

 

// C program to Find the number is odd or even using the conditional operator.

 

#include < stdio.h >

int main()

{

  int num;

  printf("Enter a number: ");

  scanf("%d", &num);

  (num%2==0) ? printf("Number is Even.") : printf("Number is Odd.");

  return 0;

}

 

Output

Enter a number: 9

Number is Odd. 

Enter a number: 4

Number is Even.

 

Conditional Operator Example for Three Variables

 

// Program to find the largest among three numbers using the conditional operator.

 

#include < stdio.h >

int main ()

{

  float x, y, z, max;

  printf("Enter three numbers: ");

  scanf("%f %f %f",&x, &y, &z);

  max = (x>y && x>y) ? x : (y>x && y>z) ? y : z;

  printf("Largest number = %.2f",max);

  return 0;

}

 

Output

Enter three numbers: 12 32 14

Largest number = 32.00

 

Take Quiz on C Programming Language.