The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements which depends upon the output of the expression. Ternary operator can be use in place of if-else statements. Ternary operator is also known as conditional operator.

C language Tutorial with programming approach for beginners and professionals, helps you to understand the C language tutorial easily. Our C tutorial explains each or every topic with example.

It is represent by two symbols, i.e., “?” and “:” .

Ternary Operators

Working on Conditional Operations or ternary operations

As conditional operator works on three operands.

  •  Expression1 is the condition to be evaluate. If the condition(Expression1) is True then,
  • Expression2 will be execute and the result will be return. Otherwise, if the condition(Expression1) is false then, 
  • Expression3 will be execute and the result will be return.

Syntax

variable = Expression1 ? Expression2 : Expression3

Flow chart of Ternary Operations

Flow Chart of Ternary Operations
FLow Chart of Ternary Operations

Example of Ternary Operations

Input value

#include <stdio.h>  
int main()  
{  
    int age;  
    printf("Enter your age");  
    scanf("%d",&age);    
    (age>=20)? (printf("eligible for voting")) : (printf("not eligible for voting"));  
    return 0;  
}  

Output of Ternary Operations

If we provide the age of user below 20 , then the output 

Output value

If we provide the age of user above 20, then the output 

Output value

Example of Ternary Operations

Write a program to find maximum of two numbers using ternary operator.

Input value

#include <stdio.h>

int main() {
  char operator = '+';
  int num1 = 42;
  int num2 = 58;

  int result = (operator == '+') ? (num1 + num2) : (num1 - num2);
  printf("%d", result);

  return 0;
}

Output of ternary operator.

Output value

If you have any queries regarding this article or if I have missed something on this topic, please feel free to add in the comment down below for the audience. See you guys in another article.

To know more about C Programming language please Wikipedia click here .

Stay Connected Stay Safe, Thank you


Basic Engineer

Hey Readers! We have more than fifteen years of experience in Software Development, IoT, Telecom, Banking, Finance and Embedded domain. Currently we are actively working on Data Science, ML and AI with multiple market leaders worldwide. Happy Reading. Cheers!

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *