The conditional operator is kind of similar to the if - statement as it does follow the same algorithm as the if-else statement, but the conditional operator takes less space and helps to write the if-else statement in the shortest way possible.
It is also called Ternary Operator means it takes three operands.
In C language programming, having three types of operators.
1. Unary operator: which operates on a single value.
2. Binary operator: which operates on two values.
3. Ternary operators: which operators on three values.
So Ternary operator takes three operands and two operators. These operators are the question mark (?) and the colon (:). The first expression is placed before the question mark (?), the second expression is in between the? and: and the third one after the colon (:).
The general format
condition ? expression 1 : expression 2;
If the condition is true then the expression 1 will be executed and if the condition is false then the expression 2 will be executed.
Example:
1. max_value = (a > b) ? a : b ;
2. sign = (number < 0 ) ? -1 : (( number ==0) ? 0 : 1);
How to use this syntax in the program?
// C program to find the square of positive numbers
#include <stdio.h>
int main()
{
int j, num;
printf("Enter your number either positive or negative \n ");
scanf("%d", &num);
j = (num < 0 ? 0 : num * num);
printf("\n The positive number's square is:%d ", j);
return 0;
}
One more example
//C program to determine the number is either negative, zero or positive
#include <stdio.h>
int main()
{
int sign, number;
printf("enter any number\n");
scanf("%d", &number);
sign = (number < 0) ? -1 : ((number == 0) ? 0 : 1);
printf("\n sign = %d", sign);
return 0;
}
Observations:
1. The conditional operator can be used in different statements (it is not used only in arithmetic statement )
ex. char a;
int y;
scanf ("% c", &a);
y = (a> = 65 &&a <= 90 ? 1 : 0 );
2. The conditional operator can be nested just like if-else-if statement.
ex. int big, a, b, c ;
big = (a > b ? (a > c ? 3 : 4) : (b > c ? 6 : 8 ));
3. Even though it is a conditional operator we need semicolon (;) at the end.
Well, do you like my post please feel free to give me comments. or subscribe to my blog for the latest post. if you want video tutors please see my youtube video for further details. https://youtu.be/jtEfH07RbgU
Nyc
ReplyDelete