Loading...
C Ternary Operator

C Ternary Operator

In this tutorial, we will learn about C ternary operator and how to use it to control the flow of program with the help of examples.


Ternary Operator

Ternary operator are a substitute for if...else statement. So before you move any further in this tutorial, go through C if...else statement (if you haven't).

The ternary operator allow us to execute different code depending on the value of a condition, the result of the expression is the result of the executed code.

The conditional operator is kind of similar to the C if...else statement as it does follow the same algorithm as of C if...else statement but the conditional operator takes less space and helps to write the if-else statement in the shortest way possible.

The Ternary operator returns one of two values depending on the result of an expression.


Syntax of Ternary Operator

The syntax of the Ternary Operator is:

Condition ? Expression1 : Expression2;

The ternary operator works as follows:

  • If the expression stated by Condition is true, the result of Expression1 is returned by the ternary operator.
  • If it is false, the result of Expression2 is returned.

For example, we can replace the following code

if (number % 2 == 0)
{
   Even = true;
}
else
{
   Even = false;
}

with

Even = (number % 2 == 0) ? true : false ;

Why is it called ternary operator?

This operator takes 3 operand, hence called ternary operator.


Example 1: C Program to find the even or odd number using Ternary Operator

// Lets understand the ternary operator to find the even or odd number

#include <stdio.h>
int main(){

    int n;
    printf << "Enter an integer: ";
    scanf >> n;
    (n % 2 == 0) ? printf << n << " is even." :  printf << n << " is odd.";

    return 0;
}

When we run the program, the output will be:

Enter an integer: 20
20 is even.

In the above program, User entered the value 20 is assigned to a variable n. Then, the ternary operator is used to check if number is even or not.

Since, 20 is even, the expression (number % 2 == 0) returns is even. We can also use ternary operator to return numbers, strings and characters.


Example 2: C Program to Find maximum number

// Program to find maximum number using ternary operator

#include <stdio.h>
int main() {

    int a = 10;
    int b = 30;
    int max = a > b ? a : b;
    printf << "Maximum Value: " << max << "\n";

    return 0;
}

When we run the program, the output will be:

Maximum Value: 30

Next Tutorial

We hope that this tutorial helped you develop better understanding of the concept of Ternary Operator in C.

Keep Learning : )

In the next tutorial, you'll learn about C For Loop.

- Related Topics