Ternary Operator in C Programming — PBA Institute Tutorial
Chapter 15 · C Programming Series
10 min read Beginner

Ternary Operator in C

The ternary operator in C, often referred to as the conditional operator, provides a shorthand method for performing conditional assignments or evaluations.

What is ternary operator ?

syntax

  • condition ? expression1 : expression2;
  • condition : A boolean expression that evaluates to either true or false.
  • expression1 : The result if the condition is true.
  • expression2 : The result if the condition is false.

How it works

The ternary operator evaluates the condition:
- If the condition is true, expression1 is executed and its value is returned.
- If the condition is false, expression2 is executed and its value is returned.

Examples

Find the maximum of a and b
#include <stdio.h>
main() {
    int a = 10;
    int b = 20;
    int max;
    max = (a > b) ? a : b;  
    printf("The maximum is %d\n", max);
}
Output
The maximum is 20
Explanation :
- The condition (a > b) checks if a is greater than b.
- If true, max is assigned the value of a.
- If false, max is assigned the value of b.
Check the number is Even or Odd
#include <stdio.h>
main() {
    int number = 7;
    printf("%d is %s\n", number, (number % 2 == 0) ? "even" : "odd"); 
}
Output
7 is odd

# . (age>=18) is the condition if the expression is true value “Allowed”is assigned to voting else “Not Allowed” will be assigned to voting. Using Ternary Operator make this program.

C Code
#include<stdio.h>
main()
{
	int a;
	printf("Enter your age:");
	scanf("%d", &a);
	printf((a>=18)?"Allowed":"Not Allowed");
}
Output
Enter your age: 20
Allowed
Write a program leap year or not without using If else statement
#include<stdio.h>
main()
{
	int y;
	printf("Enter year:");
	scanf("%d", &y);
	printf((y%4==0 && y%100!=0 || y%400==0)?"Leap-Year":"Not Leap-Year"); 
}
Output
Enter year:2004
Leap-Year

Conclusion

The ternary operator is a powerful tool in C programming that, when used appropriately, can lead to cleaner, more concise, and potentially more efficient code. It is particularly beneficial for simple conditional assignments and expressions, allowing developers to write more expressive and compact code. However, judicious use is essential to maintain code readability and clarity.