Ternary Operator in C: Usage and Examples
☰Fullscreen
Table of Content:
Ternary Operator (?:)
A conditional operator is a ternary operator, that is, it works on 3 operands.
Conditional Operator Syntax
conditionalExpression ? expression1 : expression2
The conditional operator works as follows:
- The first expression conditionalExpression is evaluated first. This expression evaluates to 1 if it's true and evaluates to 0 if it's false.
- If conditionalExpression is true, expression1 is evaluated.
- If conditionalExpression is false, expression2 is evaluated.
C conditional Operator
#includeint main(){ char February; int days; printf("If this year is leap year, enter 1. If not enter any integer: "); scanf("%c",&February); // If test condition (February == 'l') is true, days equal to 29. // If test condition (February =='l') is false, days equal to 28. days = (February == '1') ? 29 : 28; printf("Number of days in February = %d",days); return 0; }
Output
If this year is leap year, enter 1. If not enter any integer: 1 Number of days in February = 29
- Question 1: How many operators are there under the category of ternary operators?
- Question 2: What is the use of a ? character?
- Question 3: Which of the following operators is incorrect and why? ( >=, <=, <>, ==)
- Question 4: What is the syntax for ternary operator in C?
Related Questions
- Assignment 1: ? :,Conditional Expression or ternary operator
- Assignment 2: ? :,Conditional Expression or ternary operator, Find largest number among 3 numbers using ternary operator
- Assignment 3: ? :,Conditional Expression or ternary operator, Check whether Number is Odd or Even
- Assignment 4: ? :,Conditional Expression or ternary operator, same program in simple manner
- Assignment 5: ? :,Conditional Expression or ternary operator
- Assignment 6: ? :,Conditional Expression or ternary operator, Find largest number among 3 numbers using ternary operator
- Assignment 7: ? :,Conditional Expression or ternary operator, Check whether Number is Odd or Even
- Assignment 8: ? :,Conditional Expression or ternary operator, same program in simple manner
- Assignment 9: Program to show the use of a conditional operator.
- Assignment 10: Write a C program to accept all character(A to Z) and check it is even or odd place using the ternary operator (A is an odd place and B is in the even place)
- Assignment 11: Write a C program to accept a character and check it is even or odd place using the ternary operator (A is an odd place and B is in the even place)