Search code examples
cstructure

C program for salary increment calculation using structure


I would like to write a code for a C program that will:

  1. Create a structure that will store the employee details.
  2. Insert 5 different records of employees into the database.
  3. Update the salary by adding a 10% increment if the years of service is 10 years and more. Otherwise, add a 7% increment.
  4. Display the data for all employees.

My coding has satisfied item 1,2 and 4. For item 3 i have no idea how to write the coding. Can anyone enlighten me?

Below the code

#include <stdio.h>
#include <stdlib.h>
 
typedef struct{ 
    char employee_name[30];
    int employee_number;
    int salary;
    int service_year 
} Employee;
 
int main()
{
    int i, n=5;
 
    Employee employees[n];
 
    //Taking each employee detail as input
 
    printf("Enter %d Employee Details \n \n",n);
    for(i=0; i<5; i++){
 
        printf("Employee %d:- \n",i+1);
        //Name
        printf("Name: ");
        scanf("%s",employees[i].employee_name);
        //ID
        printf("Id: ");
        scanf("%d",&employees[i].employee_number);
        //Salary
        printf("Salary: ");
        scanf("%d",&employees[i].salary);
        //Year of service_year
        printf("Year of Service: ");
        scanf("%d",&employees[i].service_year);
    }
 
    //Displaying Employee details
 
    printf("-------------- All Employees Details ---------------\n");
 
    for(i=0; i<n; i++){
 
        printf("Employee Name \t: ");
        printf("%s \n",employees[i].employee_name);
 
        printf("Employee Number \t: ");
        printf("%d \n",employees[i].employee_number);
 
        printf("Salary \t: ");
        printf("%d \n",employees[i].salary);
        
        printf("Year of Service \t: ");
        printf("%d \n",employees[i].service_year);
 
        printf("\n");
    }
 
    return 0;
}

Solution

  • For item 3 i have no idea how to write the coding.
    Update the salary by adding a 10% increment if the years of service is 10 years and more. Otherwise, add a 7% increment.

    I'd avoid floating point math for an integer problem with its subtle problems.

    Add helper functions to calculate the salary increase.

    A key part of programming is to divide the task into manageable helper functions. Note the two below each handle a separate aspect of the salary adjustment. Easy enough to adjust should next years adjusts taken on a more complex calculation and not mess up other code.

    int increase_percent(int salary, int percent) {
      int half = percent >= 0 ? 100/2 : -100/2;
      return (salary * percent + half)/100; // add half for a rounded quotient
    }
    
    int increase_tenure(int salary, int years) {
      int percent = years >= 10 ? 10 : 7;
      return increase_percent(salary, percent);
    }
    
    // Usage
    employees[i].salary += increase_tenure(employees[i].salary, employees[i].service_year);