C Program To Determine Designation of Employee Based On Salary


Rewrite the following C program using Conditional / Ternary Operator.

Source Code: C Program To Determine Designation of Employee Based On Salary Using nested if else condition

#include<stdio.h>

int main()
{
    float sal;

    printf("Enter the salary\n");
    scanf("%f", &sal);

    if(sal >= 25000 && sal <= 40000)
    {
        printf("Manager\n");
    }
    else
        if(sal >= 15000 && sal < 25000)
            printf("Accountant\n");
        else
            printf("Clerk\n");

    return 0;
}

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 Operator

Related Read:
Nested if else Statement In C
Ternary Operator / Conditional Operator In C
Relational Operators In C
Logical Operators In C

Ternary / 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
40000

Output:
Manager

Logic 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 https://www.youtube.com/watch?v=W04xqRxFTHk]

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

#include<stdio.h>

int main()
{
    int sal;

    printf("Enter the salary\n");
    scanf("%d", &sal);

    ( sal >= 25000 && sal <= 40000 ) ?
    printf("Manager\n") :
    ( sal >= 15000 && sal <  25000)?
    printf("Accountant\n") :
    printf("Clerk\n");

    return 0;
}

Output 1:
Enter the salary
35000
Manager

Output 2:
Enter the salary
20000
Accountant

Output 3:
Enter the salary
10000
Clerk

Note: 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

Leave a Reply

Your email address will not be published. Required fields are marked *