Conditional Operator also known as Ternary operator is the only operator in C programming that involves three operands. This is a most popular and widely used one liner alternative of if-else statement.
Syntax of Ternary Operator:
variable = Condition ? Expression1 : Expression2;
If the Condition
is true then the Expression1
executes.
If the Condition
is false then the Expression2
executes.
Ternary Operator Example
Let’s start with a simple example. Here we have a number and we are checking whether the given number is “Positive” or “Negative” using ternary operator.
In this example:
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 are asking user to enter a number, then we are checking and printing whether the entered number is an Even number or Odd Number using ternary operator. If the condition n%2==0
is true which means that the number is perfectly divisible by 2 then the number is an Even number else 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; }
Output 1: When user entered an even number
Output 2: When user entered an odd number
Nested Ternary Operator
We can have a ternary operator inside another ternary operator. This is called nesting of conditional operators. In the following example, we are using nested ternary operator to check whether the input year is leap year or not.
Here, instead of a second expression, we have another ternary operator. This means if the condition is true, then the program prints “Leap Year”, however if the condition is false, program evaluates the nested ternary operator and prints output based on the condition in 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; }
Output 1:
Output 2: