if else vs Conditional operator in C
Notes:
if else statement vs. conditional operator in c programming language:
if else statement:
syntax:
if(conditional expression)
{
statements; // true part or true block
}
else
{
statements; // false part or false block
}
Computer executes true part; if the conditional expression inside the
parenthesis is evaluates to true, else it executes the false part.
Ex: Program to find the given number is even or odd using if else statement
#include <stdio.h>
int main()
{
int num = 11;
if(num%2==0)
{
printf("%d is even\n",num);
}
else
{
printf("%d is odd\n",num);
}
return 0;
}
Conditional Operator (?:)
- is the only ternary operator in C. It accepts 3 operands.
(operand1) ? operand2 : operand3;
Where:
operand1: must be a conditional expression
operand2: value1 // true part
operand3: value2 // false part
Ex: Program to find the given number is even or odd using conditional operator
#include <stdio.h>
int main()
{
int num = 10;
printf("%d is %s\n", num, (num%2==0) ? "even" : "odd");
return 0;
}
Note:
- Conditional operator allows us to write if else statement in a single line in condensed form