luc113.c¶
Problem Statement
Store date in a structure using bit fields (day: 5 bits, month: 4 bits, year: 12 bits). Read joining dates of 10 employees and display them sorted by year.
Metadata¶
| Property | Detail |
|---|---|
| Author | Amit Dutta amitdutta4255@gmail.com |
| Date | 08 Feb 2026 |
| License | MIT License (See the LICENSE file for details) |
Actions¶
💡 You can print or save this file by opening Raw and using your browser.
Source Code¶
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define structure with bit-fields
struct date
{
unsigned int day : 5; // 1-31 takes 5 bits
unsigned int month : 4; // 1-12 takes 4 bits
unsigned int year : 12; // Sufficient for year 0-4095
};
struct employee
{
char name[30];
struct date doj; // Date of Joining
};
int compare_dates(const void *a, const void *b);
int main()
{
struct employee emp[10];
int i;
// Temporary variables for input because we cannot take address of a bit-field
int d, m, y;
printf("Enter details for 10 employees:\n");
for (i = 0; i < 10; i++)
{
printf("\nEmployee %d Name: ", i + 1);
scanf("%s", emp[i].name);
printf("Date of Joining (dd mm yyyy): ");
scanf("%d %d %d", &d, &m, &y);
// Assign to bit-fields
emp[i].doj.day = d;
emp[i].doj.month = m;
emp[i].doj.year = y;
}
// Sort based on year using qsort
qsort(emp, 10, sizeof(struct employee), compare_dates);
printf("\n--- Employees Sorted by Joining Year ---\n");
for (i = 0; i < 10; i++)
{
printf("%-15s | DOJ: %02d-%02d-%d\n",
emp[i].name, emp[i].doj.day, emp[i].doj.month, emp[i].doj.year);
}
return 0;
}
int compare_dates(const void *a, const void *b)
{
struct employee *e1 = (struct employee *)a;
struct employee *e2 = (struct employee *)b;
// Primary sort by Year
if (e1->doj.year != e2->doj.year)
return e1->doj.year - e2->doj.year;
// Secondary sort by Month
if (e1->doj.month != e2->doj.month)
return e1->doj.month - e2->doj.month;
// Tertiary sort by Day
return e1->doj.day - e2->doj.day;
}