Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is Ternary Operator in C?
3.
Syntax of Ternary Operator in C
3.1.
Evaluation of syntax:
4.
Working of C Ternary Operator
5.
Flowchart of Conditional/Ternary Operator in C
6.
Example of C Ternary Operator
6.1.
Example 1 - 
6.2.
Example 2 - 
7.
Ternary Operator Vs. if...else Statement in C
8.
Usage of Ternary Operator in C
9.
Advantages of Ternary Operators Over If-Else Statements
10.
Frequently Asked Questions
10.1.
What is an example of a ternary operator?
10.2.
What is ternary operator for 3 conditions in C?
10.3.
What are the advantages of the conditional operator?
11.
Conclusion
Last Updated: Aug 1, 2024
Easy

Ternary Operator in C

Introduction

Starting with the C language is a great first step on your journey to becoming a skilled programmer. Why? Because C lays down the fundamental building blocks you'll need for future coding adventures. It's like learning the ABCs before diving into stories and novels. In this article, we're going to explore the Ternary Operator in C - a handy shortcut for making decisions in your code. We'll break down how it works and show you different ways to use it, all with clear examples to guide you along. Get ready to add another tool to your coding toolkit!

Ternary Operator in C

What is Ternary Operator in C?

The term ternary refers to three, symbolising the use of three operands. Thus the name ternary operator in C came up as it requires three operands. 
The ternary operator in C is used to return values according to a condition. The symbol representing the ternary operator in c is the question mark “?”. It can handle only two return values for a given condition. One is if the condition is passed, that is if the condition is true. Another one is when the condition is false.
The flowchart of the ternary operator in C is given below.

Syntax of Ternary Operator in C

The below-given syntax represents how to use a ternary operator in C.

<condition>?<return if statement is true>:<return if statement is false>;


Evaluation of syntax:

  • There are three parameters or operands used with a ternary operator in C.
     
  • First -  the condition to be followed.
     
  • Ternary operator in C (?) is used.
     
  • Second - Statement to be executed if the condition is true.
     
  • Colon is inserted.
     
  • Third - Statement to be executed if the condition is false.
     
  • End of the statement with a semicolon inserted.

Working of C Ternary Operator

A ternary operator in C works on the concept of booleans. 

The ternary operator in C works as follows:

  • Expression 1(before ?) is used to set the condition.
     
  • Expression 2(before :) is executed if the condition is true.
     
  • Expression 3(before ;) is executed if the condition is false.

Flowchart of Conditional/Ternary Operator in C

Below is the flow chart for the ternary operator.

Ternary Operator flow chart

In the above flowchart, if the given condition is true, then the "?" part will get executed, and then it goes to the expression 2. Otherwise, if the given condition is false, then the ":" part will get executed, and it goes to expression 3, and the resultant value of the expression will be assigned to the variable.

Also see, Floyd's Triangle in C

Example of C Ternary Operator

Example 1 - 

See the examples below to understand the working of ternary operators in C.

#include <stdio.h>
int main() 
{
  // Declare the variables
  int age;

  // Take user input
  printf("Enter your age: ");
  scanf("%d", &age);

  // Use ternary operator
  // Use printf function as an operand.
  (age >= 18) ? printf("Eligible to vote"): printf("Not eligible to vote");

  return 0;
}
You can also try this code with Online C Compiler
Run Code


Input

Enter your age: 19


Output

Output

We infer from the code above that:

  • Expression 1 that is age >=18 (before ?) is the condition
     
  • Expression 2 that is printf(“Eligible to vote”) (before :) is executed if the age entered is greater than or is 18 i.e., satisfies the condition.
     
  • Expression 3 that is printf("Not eligible to vote") (before ;) is executed if the age is less than 18, i.e., does not satisfy the condition.
     

Example 2 - 

Let’s look into another example to get the working of a ternary operator in C completely clear.

#include <stdio.h>
int main() 
{
  // Declare the variables
  int x;

  // Take user input
  printf("Enter a number: ");
  scanf("%d", &x);

  // Use ternary operator
  // Use printf function as an operand.
  (x % 2 == 0) ? printf("The number is even") : printf("The number is odd");

  return 0;
}
You can also try this code with Online C Compiler
Run Code


Input

Enter a number: 6


Output

Output

We infer from the code above that:

  • Expression 1, that is x % 2 == 0 (before ?), is the condition.
     
  • Expression 2 is printf(“The number is even”) (before :) is executed if the number x is completely divided by two, i.e., satisfies the condition.
     
  • Expression 3 is printf("The number is odd") (before ;) is executed if the number x leaves a remainder when divided by two, i.e., does not satisfy the condition.
     

Ternary Operator Vs. if...else Statement in C

ParametersTernary OperatorIf..else statement
SyntaxUses a single-line syntax. Hence it is more concise.Requires multiple lines and more complex syntax.
ReadabilityIt can be less readable for complex conditions or multiple actions.Generally more readable, especially for complex logic or multiple actions.
Number of ConditionsIt is limited to evaluating a single condition.It can evaluate multiple conditions using else-if clauses. 
Return ValuesIt can be used to return values for expressions.It cannot return value directly.
MaintainabilityIt is easier to maintain for simple, self-obtained conditions.It offers maintainability for complex or lengthy conditions.

Usage of Ternary Operator in C

Following are the uses of Ternary Operator in C:

  • Ternary Operator is used to assign values to a variable conditionally. For example, set a variable result to "Pass" if a score is greater than or equal to 33 and "Fail" otherwise.
     
  • It's handy for selecting different messages or outputs based on a condition. For instance, print "Yes" if a condition is true and "No" otherwise.
     
  • Ternary Operator is used to assign values to a variable when the input is missing or invalid.
     
  • Initialize elements of an array conditionally, making it easy to set specific values based on different cases.

Advantages of Ternary Operators Over If-Else Statements

Here are the advantages of ternary operators over if-else statements explained in bullet points:

  • Conciseness: Ternary operators provide a more compact and readable way to write simple conditional expressions, reducing code length.
     
  • Readability: For simple conditions, ternary operators can make the code easier to understand at a glance.
     
  • Inline Usage: Ternary operators can be used directly within expressions, such as function arguments or return statements, without needing separate lines for if-else.
     
  • Reduced Code Complexity: Using ternary operators can help avoid additional lines and braces, making the codebase cleaner.
     
  • Performance: In some languages, ternary operators can be slightly faster due to reduced overhead compared to if-else statements, though this is often negligible.
     
  • Expressiveness: They allow the expression of straightforward conditional assignments succinctly, emphasizing the assignment itself rather than the condition.
     

Also Read - Bitwise Operators in C 

Frequently Asked Questions

What is an example of a ternary operator?

An example of a ternary operator is int result = (a > b) ? a : b;, which assigns a to result if a is greater than b, and b otherwise. It's a concise way to choose between two values.

What is ternary operator for 3 conditions in C?

The ternary operator in C doesn't directly support 3 conditions in one statement. Instead, you can nest ternary operators like int result = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); for multiple conditions.

What are the advantages of the conditional operator?

The advantages of the conditional operator include concise code, reduced need for if-else statements, and the ability to embed expressions directly within other statements, leading to clearer and more compact code, especially for simple conditionals.

Conclusion

In conclusion, the ternary operator in C is a powerful and concise tool for making decisions within a single line of code. It offers a compact alternative to the traditional if-else statement when you need to assign a value based on a condition. We have studied what the ternary operator in C is, how the ternary operator in C works, and the different ways to use it. 

Refer to the Below topics for more understanding

 

Happy Learning!

Live masterclass