Codiqo

Learn C · lesson 48 of 60 · about 10 minutes

Capstone: Polishing

Sort the bill with qsort, print a tidy report, and review the code for clarity.

What you'll learn

  • Sort structs with qsort and a compare function
  • Format a report table
  • Review code for readability

The bill report

The last touch is a report the admin can read at a glance. qsort sorts the loaded costs with by_amount_desc, which puts the biggest cost first and, when two cost the same, orders them by name with strcmp, so the report always comes out the same. Then printf widths line it up: %-10s and %-8s pad the name and category on the right, %5d.%02d lines the amounts up on the dot, and the table ends with the total.

Sorting with qsort

qsort(array, count, sizeof item, compare) from stdlib.h sorts any array. You give it a compare function that receives pointers to two items and returns:

  • a negative number if the first should come first
  • a positive number if the second should come first
  • 0 if they're equal

The final report

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    char what[24];
    char category[12];
    int pence;
} Expense;

int by_amount_desc(const void *a, const void *b) {
    const Expense *x = a;
    const Expense *y = b;
    return y->pence - x->pence;
}

void report(Expense *items, int n) {
    qsort(items, n, sizeof items[0], by_amount_desc);
    int total = 0;
    printf("%-10s %-8s %8s\n", "Item", "Category", "Amount");
    for (int i = 0; i < n; i++) {
        printf("%-10s %-8s %5d.%02d\n", items[i].what, items[i].category, items[i].pence / 100, items[i].pence % 100);
        total += items[i].pence;
    }
    printf("%-19s %5d.%02d\n", "Total", total / 100, total % 100);
}

int main(void) {
    Expense items[] = {{"Bus", "travel", 205}, {"Cinema", "fun", 1150}, {"Lunch", "food", 650}};
    report(items, 3);
    return 0;
}

Output

Item       Category   Amount
Cinema     fun         11.50
Lunch      food         6.50
Bus        travel       2.05
Total                  20.05

Breaking ties

qsort doesn't promise to keep equal items in the order they started in, so two costs of 300 pence could swap places from one run to the next. Comparing a second thing when the first is equal, here the name with strcmp, means no two costs are ever equal unless they're the same cost, and the report is the same every time.

Amount first, then name

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    char what[8];
    int pence;
} Cost;

int by_amount_then_name(const void *a, const void *b) {
    const Cost *x = a;
    const Cost *y = b;
    if (x->pence != y->pence) {
        return y->pence - x->pence;
    }
    return strcmp(x->what, y->what);
}

int main(void) {
    Cost costs[] = {{"mail", 300}, {"cdn", 450}, {"dns", 300}};
    qsort(costs, 3, sizeof costs[0], by_amount_then_name);
    for (int i = 0; i < 3; i++) {
        printf("%s ", costs[i].what);
    }
    printf("\n");
    return 0;
}

Output

cdn dns mail

A final review

Read your code as if someone else wrote it:

  • Does every function do one job, with a clear name?
  • Is every malloc freed and every fopen checked and closed?
  • Are fixed sizes named with #define instead of repeated numbers?
  • Does the program handle bad input without crashing?

Tip

You've built a real C program: structs, functions, input parsing, files, error handling and sorting. Try adding a delete command or monthly totals next.

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.