Review the key points with a cheat sheet, six code-reading questions, and a checklist of common mistakes.
#include <stdio.h> int main(void) { printf("Hello\n"); return 0; }
| Type | Example | printf | scanf |
|---|---|---|---|
| int | 42 | %d | %d |
| double | 3.14 | %f | %lf |
%.2f(two decimal places) %5d(right-aligned in five columns), for example. printf("x=%d, y=%d\n", x, y); printf("%.2f", 3.146); // → 3.15 (rounded) printf("%5d", 42); // → 42 (right-aligned in five columns) printf("%05d", 42); // → 00042 (zero-padded)
%d or %f in the format string requires a corresponding argument, in order.int n; scanf("%d", &n); // & is required! double x; scanf("%lf", &x); // Use %lf for double
%f). int a = 10; // a:10 int b = 30; // b:30 b = a; // b:10 (30 is overwritten) a = 5; // a:5 (10 is overwritten) // Result: a=5, b=10
int a = 10, b = 30; b = a; a = 5; printf("%d %d\n", a, b);
5 10.int x = 7; printf("%f\n", x);
%f expects a double argument, but n is int. This mismatch causes undefined behavior, so no particular output is guaranteed. A compiler may warn without rejecting the program. Use %d for int and %f for double.double a = 3.146, b = 3.144; printf("%.2f %.2f\n", a, b);
%.2f prints two decimal places with rounding. 3.146 rounds to 3.15, while 3.144 rounds to 3.14. Floating-point approximations and the rounding mode can matter at exact halfway boundaries; these examples avoid that boundary.printf("x=%d", 3); printf("y=%d\n", 7);
x=3 and the second immediately appends y=7, producing x=3y=7. Include \n wherever a newline is required.int n; scanf("%d", n); // & is missing printf("%d\n", n);
& passes an uninitialized int instead of a valid pointer, causing undefined behavior and potentially a segmentation fault. A warning does not necessarily prevent compilation. Use scanf("%d", &n).double x; scanf("???", &x); printf("%f\n", x);
%lf (lowercase L, then f) to read a double with scanf. printf accepts %f and %lf for double, but scanf requires %f for float* and %lf for double*.scanf("%d", &n), not scanf("%d", n). scanf needs an address. A character array used as a string does not need an extra &.\n where needed. ;missing ;, check one or two lines before the reported location. "x=%d, y=%d"requires the following arguments in the order x, then y . Reversing them reverses the displayed values. =with comparison ==operators a = 5means store 5 in a; a == 5asks whether a equals 5.