How to use printf and scanf in C. A complete reference of format specifiers.
printf displays a string (a sequence of characters) on the screen.\n is a special escape sequence that means "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
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)scanf is a function that reads input from the keyboard. It essentially does the opposite of printf.
int a; printf("Enter a value for a: "); scanf("%d", &a); // Don't forget the &! double b; printf("Enter a value for b: "); scanf("%lf", &b); // double uses %lf (NOT %f)
scanf("%d", &a);scanf("%lf", &b);\n in the format string.int → scanf: %d / printf: %ddouble → scanf: %lf / printf: %f
Check your understanding of this lesson!
%d is the format specifier for integers. The value 10 is printed as-is.
scanf requires the address of the variable, so you must prefix it with & (the address-of operator).
%.2f prints a floating-point number with two digits after the decimal point. 3.14159 becomes 3.14.