In this video tutorial we will show you how to use Conditional Operator. They are also called Ternary Operators as they take 3 arguments.
General Form of Ternary Operator
(expression_1) ? (expression_2) : (expression_3);
expression_1 is a comparison/conditional argument. expression_2 is executed/returned if expression_1 results in true, expression_3 gets executed/returned if expression_1 is false.
Ternary operator / Conditional Operator can be assumed to be shortened way of writing an if-else statement.
C Program: Ternary Operator / Conditional Operator
#include < stdio.h > int main() { int a = 1, b = 1, c; // (expression1) ? (expression2) : (expression3); (a+b) ? (c = 10) : (c = 20); printf("Value of C is %d\n", c); return 0; }
Output:
Value of C is 10
a+b is 2 which is non-zero, so it is considered as true. So c = 10 gets executed.
#include < stdio.h > int main() { int a = 1, b = 1, c; // (expression1) ? (expression2) : (expression3); (a-b) ? (c = 10) : (c = 20); printf("Value of C is %d\n", c); return 0; }
Output:
Value of C is 20
a-b is 0 which is zero, so it is considered as false. So c = 20 gets executed.
#include < stdio.h > int main() { int a = 1, b = 1, c; // (expression1) ? (expression2) : (expression3); c = (a+b) ? (10) : (20); printf("Value of C is %d\n", c); return 0; }
Output:
Value of C is 10
#include < stdio.h > int main() { int a = 1, b = 1, c; // (expression1) ? (expression2) : (expression3); c = (a-b) ? (10) : (20); printf("Value of C is %d\n", c); return 0; }
Output:
Value of C is 20
Ternary Operator / Conditional Operator In C
[youtube https://www.youtube.com/watch?v=wubWvdcjMcw]
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert