C

Examples Of The Conditional (Ternary) Operator In C

The Conditional Operator, also known as the Ternary Operator in C programming, is the only operator with three operands. This is the most common and widely used one-liner if-else statement alternative.
Ternary Operator Syntax:

variable = Condition ? Expression1 : Expression2;

Example of a Ternary Operator

Begin with a simple example. We have a number and are using the ternary operator to determine whether it is “Positive” or “Negative.”
In this case:

Condition: number<0
Expression1: printf("Negative Number")
Expression2: printf("Positive Number")

#include <stdio.h>
int main ()
{
  int number = -10;

  //ternary operator to print whether the given number is
  // positive or Negative.
  (number<0)? (printf("Negative Number")) : (printf("Positive Number"));

  return 0;
}

Output:

Negative Number

Example 2: In the following example, we ask the user to enter a number, and then we use the ternary operator to determine whether the entered number is an even or odd number. If the condition n%2==0 holds true, indicating that the number is perfectly divisible by 2, the number is an even number; otherwise, the number is an odd number.

#include <stdio.h>
int main ()
{
  int num;

  //Asking user to enter a number
  printf("Enter any number: ");

  //storing the user entered number in variable "num"
  scanf("%d",&num);

  //check even or odd number using ternary operator
  (num%2==0)? (printf("Even Number.")) : (printf("Odd Number."));

  return 0;
}

Ternary Nested Operator

A ternary operator can be contained within another ternary operator. This is known as conditional operator nesting. In the following example, we use a nested ternary operator to determine whether or not the input year is a leap year.
Instead of a second expression, another ternary operator is used here. This means that if the condition is true, the program prints “Leap Year,” but if it is false, the program evaluates the nested ternary operator and prints output based on the condition in the nested ternary operator.

#include <stdio.h>
int main ()
{
  int year;

  //taking year data from the user
  printf("Enter any year: ");
  scanf("%d", &year);

  //checking leap year using nested ternary operator
  (year%4==0 && year%100!=0) ? printf("Leap Year") :
          (year%400 ==0 ) ? printf("Leap Year") : printf("Not a Leap Year");

return 0;
}

Related Articles

Leave a Reply

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

Back to top button