Lesson 4 · 4 of 20
printf formats · C
Master printf format specifiers in C: %d, %f, %c and %s, decimals with %.2f, column widths, %% and other formats for a shop receipt.

Every % in a printf text is a format specifier: a slot filled with the next value in the list, in order. %d is for int, %f for double, %c for char and `%s` for text. The type must match; otherwise the result is unpredictable (and -Wall warns you).
Between the % and the letter you can set the precision: %.2f prints two decimals (42.75) and %.0f rounds to a whole number (43).
A number in front is the minimum width of the column. %5d pads with spaces on the left up to 5 characters (right-aligned), %-5d aligns left and %05d pads with zeros. Put together, as in %-10s %4d %8.2f, they make the columns of the receipt.
To print a percent sign, write `%%`. There are other handy formats too: %x prints a number in hexadecimal (255 is ff) and %e in scientific notation.
Code · main.c
#include <stdio.h>int main(void) { int items = 3; double total = 42.75; char size = 'M'; // %d int, %f double, %c char, %s text printf("%d items, size %c, %s\n", items, size, "paid"); // .2 means two decimals; .0 rounds to a whole number. printf("Total: %.2f euros\n", total); printf("Total: %.0f euros (rounded)\n", total); // A width pads the value: right-aligned by default, - aligns left. printf("[%5d] [%-5d] [%05d]\n", 42, 42, 42); // A small receipt in columns. printf("%-10s %4s %8s\n", "Product", "Qty", "Price"); printf("%-10s %4d %8.2f\n", "T-shirt", 2, 15.0); printf("%-10s %4d %8.2f\n", "Cap", 1, 12.5); printf("%-10s %4d %8.2f\n", "Socks", 3, 4.99); // %% writes a percent sign. printf("Discount: %d%%\n", 15); // %x shows hexadecimal, %e scientific notation. printf("255 in hex: %x, big number: %e\n", 255, 123456.0); return 0;}Output · cc main.c -o main && ./main
3 items, size M, paid Total: 42.75 euros Total: 43 euros (rounded) [ 42] [42 ] [00042] Product Qty Price T-shirt 2 15.00 Cap 1 12.50 Socks 3 4.99 Discount: 15% 255 in hex: ff, big number: 1.234560e+05
Key points
%dint,%fdouble,%cchar,%stext.%.2fsets the number of decimals.%8dtakes 8 characters;%-8saligns left.%%prints a%sign.
Exercise
Add a total line to the receipt (quantity times price for each product, added up) lined up under the Price column.