🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Integer Payroll Using Structures
Compute DA, HRA and total salary with exact integer money and sort in descending order.
Integer Payroll Using Structures in C
Every free C programming course eventually asks you to compute a salary, and this lecture does it the way embedded engineers prefer: with whole numbers instead of floating point. The exercise is simple to state. Accept five employee records with name, age and basic pay. The total salary is the basic pay plus a dearness allowance (DA) of 10 percent plus a house rent allowance (HRA) of 5 percent. Then display the name, age and total, ordered from highest to lowest total.
The first half of the solution is arithmetic and the second half is sorting. The interesting design question is where to keep the computed values. This lecture answers it with a second structure, and shows how embedded C programming avoids rounding errors by counting in the smallest unit of money.
What You Will Learn
- How to keep input data and computed data in two related structures
- Why money should be stored as an integer count of paise instead of a float
- How to turn percentages into exact integer arithmetic
- How to sort in descending order with
qsort() - How to break ties so that the output is the same on every run
- How to print rupees and paise from one integer without a float
Prerequisites
You should be comfortable with structures containing arrays, nested structures, qsort() from the previous lecture, and the integer division and modulo operators. This is part of the free embedded C course structure chapter.
Two Structures, One Responsibility Each
The employee structure from the exercise has only three members: name, age and basic pay. DA, HRA and the total are not facts about the employee; they are results of a calculation. Stuffing them into the same structure mixes input with output. A cleaner design wraps the employee inside a payslip structure that adds the derived numbers.
Nesting the whole employee, rather than copying its fields, means the original record stays intact and the payslip can be thrown away and recomputed at any time.
Why Paise and Not Floats
A float cannot represent 0.1 exactly, and adding allowances in floating point can leave a total like 59799.99998. On a microcontroller without a floating point unit, float arithmetic also pulls in a large software library. Counting in paise (one hundredth of a rupee) makes every amount an exact integer.
| Item | Formula in rupees | Formula in paise (basic in whole rupees) |
|---|---|---|
| DA | basic × 10 / 100 | basic × 10 |
| HRA | basic × 5 / 100 | basic × 5 |
| Total | basic + DA + HRA | basic × 100 + DA + HRA |
Take basic pay of 52000 rupees. DA is 5200.00 rupees, which is 520000 paise, which equals 52000 * 10. The percentages work out exactly because 10 percent of N rupees is N times 10 paise. Printing needs only integer division by 100 for rupees and modulo 100 for the paise, formatted with %02ld so that 5 paise appears as 05.
Note:
If basic pay itself can contain paise, store it in paise from the start. The rule is to pick one smallest unit and never mix units inside a calculation.
Descending Order and Tie Breaking
The comparator for descending order is the ascending one with its arguments reversed. Two employees can earn the same total, so the comparator needs a second rule: when totals are equal, order by name. Without it the order of tied rows would depend on the sorting algorithm, and test results would look inconsistent between machines.
The Complete Program
The program defines five employees directly in an initialiser list so you can focus on the logic; replacing it with the input loop from lecture 57 is a good exercise. Two employees, Anita and Meena, have the same basic pay on purpose so you can see the tie break in action.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct employee {
char name[25];
int age;
int basic; /* whole rupees */
};
struct payslip {
struct employee emp;
long da_paise;
long hra_paise;
long total_paise; /* everything in paise: no floating point needed */
};
static void compute(struct payslip *p)
{
p->da_paise = (long)p->emp.basic * 10; /* 10% of basic rupees = basic*10 paise */
p->hra_paise = (long)p->emp.basic * 5; /* 5% of basic rupees = basic*5 paise */
p->total_paise = (long)p->emp.basic * 100 + p->da_paise + p->hra_paise;
}
/* Descending by total, ties broken by name so output is repeatable. */
static int by_total_desc(const void *pa, const void *pb)
{
const struct payslip *a = pa;
const struct payslip *b = pb;
if (a->total_paise != b->total_paise) {
return (b->total_paise > a->total_paise) - (b->total_paise < a->total_paise);
}
return strcmp(a->emp.name, b->emp.name);
}
int main(void)
{
struct payslip staff[] = {
{{"Ravi", 31, 52000}, 0, 0, 0},
{{"Anita", 27, 48000}, 0, 0, 0},
{{"Kiran", 35, 61000}, 0, 0, 0},
{{"Meena", 29, 48000}, 0, 0, 0},
{{"Zoya", 41, 75500}, 0, 0, 0},
};
size_t n = sizeof staff / sizeof staff[0];
for (size_t i = 0; i < n; i++) {
compute(&staff[i]);
}
qsort(staff, n, sizeof staff[0], by_total_desc);
printf("%-8s %3s %9s %9s %9s\n", "name", "age", "DA", "HRA", "total");
for (size_t i = 0; i < n; i++) {
const struct payslip *p = &staff[i];
printf("%-8s %3d %6ld.%02ld %6ld.%02ld %6ld.%02ld\n",
p->emp.name, p->emp.age,
p->da_paise / 100, p->da_paise % 100,
p->hra_paise / 100, p->hra_paise % 100,
p->total_paise / 100, p->total_paise % 100);
}
return 0;
}Build and Run
gcc -std=c11 -Wall -Wextra -o ep_payroll ep_payroll.c
./ep_payrollname age DA HRA total
Zoya 41 7550.00 3775.00 86825.00
Kiran 35 6100.00 3050.00 70150.00
Ravi 31 5200.00 2600.00 59800.00
Anita 27 4800.00 2400.00 55200.00
Meena 29 4800.00 2400.00 55200.00Check one row by hand. Kiran earns a basic of 61000. DA is 6100, HRA is 3050, and 61000 + 6100 + 3050 is 70150. The table agrees, and Anita appears before Meena at 55200 because of the name tie break.
Reading the Program Line by Line
The compute() function is the heart of the solution and is only four lines long. It multiplies the basic pay by ten to get DA, by five to get HRA, and adds the three parts for the total, all in paise. Because every value is a long, the multiplication happens in a type wide enough for typical salaries even where int is small.
In main() the employees are listed with brace initialisers, one set of braces for the nested employee and the remaining three zeros for the derived members. A loop calls compute() on each payslip, qsort() orders them, and a final loop prints one formatted row per employee. The format string uses %6ld.%02ld, which prints the rupee part right-aligned in six columns, a decimal point, and exactly two digits of paise.
Try changing the program yourself. Raise the DA rate to 12 percent by changing a single multiplier. Add a deduction of 2 percent for provident fund and subtract it from the total. Add a sixth employee whose pay ties with two others and confirm that the order is still decided by name. Each change touches exactly one function, which is the payoff of keeping the calculation separate from the display.
Common Mistakes and Troubleshooting
| Mistake | Result | Fix |
|---|---|---|
Computing basic * 10 / 100 in integers | Truncation loses fractions for small values | Work in paise so no division is needed |
Using int for paise totals | Overflow on large salaries with 16-bit int | Use long or int32_t/int64_t |
Forgetting the %02ld | 5 paise prints as .5 | Pad with zero |
| Sorting ascending by mistake | Lowest salary first | Reverse the comparison |
| No tie break | Output order changes between runs | Add a secondary key such as name |
| Storing totals in the employee structure | Input and results mixed, stale values after edits | Keep a separate derived structure |
Warning:
On a 16-bit microcontroller int is only 16 bits wide, so basic * 115 for a basic of 52000 does not fit. The program uses long for that reason. Check your target’s integer sizes before choosing types.
Best Practices
- Use integers for money in every embedded project; convert to text only when displaying.
- Separate input structures from computed structures.
- Write one function for the calculation (
compute()) so the formulas live in one place. - Always make comparators deterministic with a tie breaker.
- Name the unit in the variable:
total_paiseis self-documenting.
Performance and security notes:
Integer arithmetic is faster than float on most microcontrollers and gives bit-exact results on every platform. Validate input ranges before multiplying; an absurdly large basic pay can overflow the multiplication and produce a small, wrong total.
Extending the Exercise
Once the basic version works, try three extensions. First, read the employees from the keyboard using the safe line-reading helpers from the first lecture of this series. Second, print a total row at the bottom that adds every employee’s total, using a long accumulator. Third, let the user choose the sort key at run time by keeping three comparator functions and selecting one through a function pointer. These extensions use only ideas you already know, and together they turn a classroom exercise into a small but realistic payroll tool.
Summary and Key Takeaways
- A payslip structure can wrap an employee structure and add computed fields.
- Paise arithmetic makes percentages exact with no floating point.
- Descending sort is the ascending comparator with the arguments swapped.
- A tie breaker makes sorted output repeatable.
- Print money by dividing and taking the remainder of 100.
Conclusion
You solved a payroll exercise using structures, nested structures, integer money and qsort() all at once, and each piece is reusable in firmware that handles prices, counters or sensor scaling. The next lectures in this free C programming course move to linked lists, starting with joining two lists and rotating the first node to the end.
Frequently Asked Questions
Why not store the salary as a double?
Doubles cannot hold most decimal fractions exactly, so totals can drift by tiny amounts. Integers in the smallest unit are exact.
Is 10 percent of basic really basic times 10 paise?
Yes. Ten percent of N rupees is N/10 rupees, which is N times 10 paise.
Why does the payslip contain a whole employee instead of just the name?
It keeps the original record intact and makes it easy to print age and name from the same place.
How do I sort ascending instead?
Swap the two totals in the comparator, or reverse the sign of its result.
What type should I use for money on a 32-bit microcontroller?
A signed 32-bit or 64-bit integer, depending on the largest amount you must hold, with the unit in the name.
Can qsort sort a nested structure?
Yes. It treats each array element as a block of bytes; your comparator decides which members matter.
Keep Learning C for Free
Practise more structure exercises and embedded C programming with the next free lecture.

2 Comments