The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
The conditional operator is sometimes called a ternary operator because it involves three operands. It is best understood by considering the following example
younger = son < father ? 18 : 40;
In the above example, son's age is 18 whereas father's age is 40. But we need the younger age so we make use of conditional operator to extract least age.
condition ? (value 1) : (value 2)
Conditional operator performs nothing more special. It is the abstraction of if else statement. Consider the following example how Condtional Operator works
younger = true ? 18 : 40;
If the logical expression resulted true, 18 will be stored in a variable younger.
younger = false ? 18 : 40;
If the logical expression resulted true, 40 will be stored in a variable younger.
Here we are to find the least age and store it in a variable younger_age without using Conditional operator.
#include <stdio.h> //header file section int main() //main section { int son = 18; int father = 40; int younger_age; if(son < father) younger_age = son; else younger_age = father; printf("%d is the younger age", younger_age); return 0; }
Here the code looks more verbose as we make use of if else statement.
Here we are to find the least age and store it in a variable younger_age using Conditional operator.
#include <stdio.h> //header file section int main() //main section { int son = 18; int father = 40; int younger_age; younger_age = son < father ? son : father; printf("%d is the younger age", younger_age); return 0; }
In line 7, Conditional Operator is get used to reduce the size of the program.
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019