How to use C printf with format specifiers. Interactive tester for %d / %f / %s / width / precision.
printf("...%d...\n", x); prints a value%d=int, %f=double, %c=char, %s=stringscanf("%d", &x); reads input β don't forget &\n is newline%5d, %.2f)%x (hex), %o (octal)printf prints a string (a sequence of characters) to the screen.\n is an escape sequence meaning "newline."
printf("Hello World!\n"); // Print a string printf("5 x 6 = %d\n", 30); // Embed a number inside the string printf("result = %d\n", value); // Display a variable's value
printf, the format specifier has to match the variable's type.int a = 5;printf("%d", a); → 5%2d → " 5", %4d → " 5"double b = 5.23;printf("%f", b); → 5.230000%5.2f → " 1.52" (width 5, 2 decimals)%f for an int or %d for a double produces zero or undefined values.% specifiers to the format string and list the variables in the same order after the comma. The first % pairs with the first variable, the second % with the second, and so on.%d β age, second %.1f β h. They're filled in the order you list them.% specifiers = number of arguments after the comma. A mismatch prints garbage.printf("%d + %d = %d\n", a, b, a+b); β 3 + 5 = 8%f prints six digits after the decimal point. So 3.14 comes out as 3.140000 β a lot of noise. The precision specifier lets you tame that.%.Nf β N digits after the decimal point| Format | Meaning | Output for b = 3.14159 |
|---|---|---|
%f | Default (6 decimal digits) | 3.141590 |
%.0f | Integer part only (rounded) | 3 |
%.1f | 1 decimal digit (rounded) | 3.1 |
%.2f | 2 decimal digits (common β currency, %) | 3.14 |
%.4f | 4 decimal digits (physics/science) | 3.1416 |
%8.2f | Width 8, right-aligned, 2 decimal digits | " 3.14" |
%-8.2f | Width 8, left-aligned, 2 decimal digits | "3.14 " |
%08.2f | Width 8, zero-padded, 2 decimal digits | "00003.14" |
%W.Nf, W is the total width (including the decimal point) and N is the number of digits after the decimal point. You can omit either one (%.3f, %10f).double x = 3.145;printf("%.2f", x); β 3.15 (rounded up)double y = 3.144;printf("%.2f", y); β 3.14 (rounded down)double v = 0.00000123;printf("%.2f", v); β 0.00 (information is lost!)printf("%.2e", v); β 1.23e-06 (scientific notation)printf("%g", v); β 1.23e-06 (whichever form is shorter)%e or %g preserves the meaningful digits.
scanf is replaced by a prompt dialog.printf with %d %d %d to print three variables at once%5d, %.3f, %-10s\n (newline) and \t (tab) to align text%c (char), %x (hex), and %o (octal)Check your understanding of this lesson!
%d is the format specifier for integers, so the value 10 is printed as-is.
scanf needs the variable's address, so you prefix the variable with & (the address-of operator).
%.2f prints a floating-point number with two digits after the decimal point, so 3.14159 becomes 3.14.