Ternary operator is the operator is used similarly as if-else conditions.
If-else condition :-
Syntax ::
If(condition)
Statement 1;
Else
Statement 2;
It means when the condition given in "IF" will be true then "STATEMENT 1" will execute otherwise when condition is false then "STATEMENT 2" will execute.
Ternary Operator :-
Syntax ::
Condition ? Statement 1 : Statement 2 ;
Here,
First we write condition, then put a question mark (?), then write statement 1, then put a colon (:), then write statement 2, then finally put a semicolon (;).
When condition is true then statement 1 will execute otherwise statement 2 will execute.
Example :- To find whether the number is even or odd.
Method 1 - By using if-else
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
puts("Enter the number");
scanf("%d",&x);
if(x%2==0)
puts("even")
else
puts("odd");
}
Method 2 - By using ternary operator
#include<stdio.h>
#include<conio.h>
void main()
{
int x;
puts("Enter the number");
scanf("%d",&x);
x%2==0?puts("even"):puts("odd");
}
Comments
Post a Comment