Conditional Operator in C [ Full Information With Examples ]

Conditional Operator in C
Conditional Operator in C Language

Conditional Operator in C

Conditional Operator is a ternary operator as it works on three operands. The Conditional Operator behaves like an if-else statement

With the help of Conditional Operator, we can also do all the work done by if-else.

With the conditional operator, we can write code using very few lines.

Conditional statements are represented by two symbols, namely, ‘? Is represented by ‘and’: ‘. (?:)

Syntax of Conditional Operator In C

Expression1? expression2: expression3;

Look at this syntax, if the condition of Expression1 is True, then Expression2 runs or else Expression3 runs.

Example – Conditional Operator In C

We are going to create such a program with the help of conditional operator.

In which we will say the user to enter his age. Then they will check the age entered by them and tell them whether the user is eligible for voting or not.

If the user is eligible for voting, then we will print “eligible for voting” in the output, otherwise, we will print “not eligible for voting”.

#include <stdio.h>
int main ()
{
    int age; // variable declaration
   
    printf("Enter your age \n");
    scanf("%d", &age); // taking user input for age variable
    // conditional operator
   (age>=18)? (printf ("eligible for voting")) :( printf ("not eligible for voting"));
 return 0;
}

See the above example, in that we asked the user to enter his age and (age> = 18), check whether the age of the user is 18 or 18+.

Let’s see, if the age of the user was less than 18, what would have come in the output and if it was more than 18, then what would have come in the output?

Input 1-:

Enter your age
24
eligible for voting

The age of the user is more than 18, so “eligible for voting” was printed in the output.

Input 2 -:

Enter your age
14
Not eligible for voting

The age of the user is less than 18, so “Not eligible for voting” was printed in the output.

Conclusion -:

Friends, I hope that after reading this post today, you have learned What is Conditional Operator in C language? And how to use it in C language? 

Friends, I hope you have found the answer of your question and you will not have to search about the Conditional Operator in C language.

However, if you want any information related to this post or related to programming language, computer science, then comment below I will clear your all doubts 

Friends, if you liked this post, then definitely share this post with your friends so that they can get information about the Conditional Operator in C Language. 

To get the information related to Programming Language, Coding, C, C ++, subscribe to our website newsletter. So that you will get information about our upcoming new posts soon.

Leave a Comment