Rewrite the following C program using Conditional / Ternary Operator.
Page Contents
Source Code: C Program To Determine Designation of Employee Based On Salary Using nested if else condition
#includeint main() { float sal; printf("Enter the salary\n"); scanf("%f", &sal); if(sal >= 25000 && sal = 15000 && sal Note: We need to rewrite the above C program using Ternary / Conditional Operator.
Good Example of Nested Ternary Operator
C Program To Check Leap Year Using Ternary OperatorRelated Read:
Nested if else Statement In C
Ternary Operator / Conditional Operator In C
Relational Operators In C
Logical Operators In CTernary / Conditional Operator General Form
(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.
Expected Output for the Input
User Input:
Enter the salary
40000Output:
ManagerLogic To Convert from if else To Conditional Operator
As you can see we’ve nested if else statement inside first else statement. So we’ll have nested conditional operator inside expression_3 of outer conditional operator.
Video Tutorial: C Program To Determine Designation of Employee Based On Salary
YouTube Link: https://www.youtube.com/watch?v=W04xqRxFTHk [Watch the Video In Full Screen.]Source Code: C Program To Determine Designation of Employee Based On Salary using Conditional Operator
#includeint main() { int sal; printf("Enter the salary\n"); scanf("%d", &sal); ( sal >= 25000 && sal = 15000 && sal Output 1:
Enter the salary
35000
ManagerOutput 2:
Enter the salary
20000
AccountantOutput 3:
Enter the salary
10000
ClerkNote: As you can see if you enter the salary as $40001 and above, it shows the designation as Clerk. That is because we’re not checking for salary above $40000. With the problem statement given above, we assume that this C program is for employees with salary less than $40000 and for designation Manager, Accountant and Clerk only.
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