Ternary operator

We can use ternary operator instead of if..else statement. It will take three arguments.

First argument is comparison statement.

Second argument will be executed, if the comparison becomes true.

Third argument will be executed, if the comparison becomes false.




Syntax

Example

argument1 ? argument 2 : argument 3;

It is as same as below,

Example

if (argument 1)                 
     argument 2;
else                           
     argument 3; 





Example

Check whether the given number is positive or negative.


Example

#include<stdio.h>

int main()
{
    int num;
 
    scanf("%d",&num);
 
    num < 0 ? printf("Negative") : printf("Positive");
 
    return 0;

}

We can also write the same program by using if..else like below,

Example

#include<stdio.h>

int main()
{
    int num;
 
    scanf("%d",&num);
 
    if(num < 0)
        printf("Negative");
    else
        printf("Positive");
 
    return 0;
}


Topics You Might Like