Write a C program to store n employee records based on EMP_ID,EMP_NAME,EMP_DEPTID,EMP_PHNO,EMP_SALARY and display all the details of employees using EMP_NAME in sorted order
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define a structure to represent an employee
typedef struct {
int emp_id;
char emp_name[50];
int emp_deptid;
char emp_phno[15];
float emp_salary;
} Employee;
// Function to read employee details
void readEmployee(Employee *employee) {
printf("Enter Employee ID: ");
scanf("%d", &employee->emp_id);
printf("Enter Employee Name: ");
scanf(" %[^\n]%*c", employee->emp_name); // Read string with spaces
printf("Enter Employee Department ID: ");
scanf("%d", &employee->emp_deptid);
printf("Enter Employee Phone Number: ");
scanf(" %[^\n]%*c", employee->emp_phno);
printf("Enter Employee Salary: ");
scanf("%f", &employee->emp_salary);
}
// Function to display employee details
void displayEmployee(const Employee employee) {
printf("Employee ID: %d\n", employee.emp_id);
printf("Employee Name: %s\n", employee.emp_name);
printf("Employee Department ID: %d\n", employee.emp_deptid);
printf("Employee Phone Number: %s\n", employee.emp_phno);
printf("Employee Salary: %.2f\n", employee.emp_salary);
}
// Comparator function for qsort to sort employees by name
int compareByName(const void *a, const void *b) {
Employee *employeeA = (Employee *)a;
Employee *employeeB = (Employee *)b;
return strcmp(employeeA->emp_name, employeeB->emp_name);
}
int main() {
int n;
printf("Enter the number of employees: ");
scanf("%d", &n);
// Allocate memory for n employees
Employee *employees = (Employee *)malloc(n * sizeof(Employee));
// Read employee details
for (int i = 0; i < n; i++) {
printf("\nEnter details for employee %d:\n", i + 1);
readEmployee(&employees[i]);
}
// Sort employees by name
qsort(employees, n, sizeof(Employee), compareByName);
// Display sorted employee list
printf("\nEmployee list sorted by name:\n");
for (int i = 0; i < n; i++) {
displayEmployee(employees[i]);
printf("\n");
}
// Free the allocated memory
free(employees);
return 0;
}
Comments
Post a Comment