The Conditional Operator in C, also called a Ternary, is used in decision-making. In this C programming language, the conditional or ternary Operator returns the statement depending upon the given expression result.
The basic syntax of a Ternary or conditional Operator in C Programming is as shown below:
Test_expression ? statement1: statement2
From the above syntax, If the given test condition is true, then it returns statement1, and if it is false, statement2 will return.
Ternary or Conditional Operator in C Example
In this program, we use the Conditional to find whether the person is eligible to vote or not. This ternary operator program allows the user to enter his or her age and assign the user entered integer value to the age variable.
If the user entered a value is 18 or above, the C Programming will print the first statement after the ? symbol ” You are eligible to Vote “.
If the user enters below 18, the second statement (which is after the : symbol) will print. ” You are not eligible to Vote “.
#include<stdio.h> int main() { int age; printf(" Please Enter your age here: \n "); scanf(" %d ", &age); (age >= 18) ? printf(" You are eligible to Vote ") : printf(" You are not eligible to Vote "); return 0; }
Let us try with a different value as the age to explain the conditional Operator.
Please Enter your age here:
19
You are eligible to Vote