Ternary Operators in C

ternary operators in C

What are ternary Operators ?

C language has many different types of operators, which help the programmer in instructing the compiler to perform various different operations on the given set of data. From many different types of operators, one which is widely used by the programmers is the ternary operator in C programming language.

How to use a Ternary Operator ?

A ternary operator in C programming is used for decision making. It has three parts:

  • The condition part- which defines the condition which we are choosing upon
  • The first statement  – which decides that what will happen, if the condition is true.
  • The second statement part – which decides that what will happen, if the condition is false.

Syntax for Ternary Operator

  • condition ? statement 1 : statement 2 ;

Ternary operator can be taken as a substitute for other decision making statements, like if, if else, etc. as it helps in raising a condition and deciding the output, based on the condition, it is also favourable, because:

  • uses less space than if-else statement.
  • decreases the complexity of the program
  • Easy to understand
Competitive Coding Techniques
#include<stdio.h>
int main()
{
       int a=0,b=0, max;
       printf("Enter first number : ");
       scanf("%d", &a);
       printf("Enter first number : ");
       scanf("%d", &b);
       max = a>b ? a : b ;
       printf("The larger number is %d", max);

}
Output
Enter first number : 10
Enter second number : 5
The larger number is 10

One comment on “Ternary Operators in C”