Multiple Variables
Specifiers are matched with variables in exact sequential order.
Programs need data to work with, and a way to show results. C provides standard library functions to communicate with the console.
scanf("%d", age); and forget the & symbol?printf Format SpecifiersThe printf function replaces format specifiers (like %d or %f) with the values of the variables provided after the comma.
Specifiers are matched with variables in exact sequential order.
Control alignment and decimal places inside the % symbol.
scanf needs the & (Address) OperatorWhen a delivery person brings a package, they need your home address, not just your name. scanf works the exact same way.
Try delivering the value 42 to the variable score.
&scanf("%d", score);
You are passing the value `10` to scanf. Scanf tries to deliver the input to memory address `0x0000000A` (10), which belongs to the operating system. Crash!
&scanf("%d", &score);
You are passing the address `0x7FFE`. Scanf goes to that exact address and deposits the user's input safely.
\n) TrapWhen you type a number and press Enter, both the number and a newline character \n enter the keyboard buffer. scanf("%d") reads the number but leaves the \n behind!
Scenario: The user typed 42, pressed Enter, then typed Y and pressed Enter.
%d automatically ignores leading spaces, reads the digits, and stops exactly at the first non-digit (the \n).
Unlike %d, the %c specifier reads the very next character in the buffer, even if it is a newline!
getchar and putcharWhile `printf` and `scanf` are versatile, C provides specialized, faster functions when you only need to read or write a single character.
getchar()Reads a single character directly from the standard input (keyboard buffer).
putchar()Writes a single character directly to the standard output (screen).
Ensure the number and type of % format specifiers exactly match the variables you provide.
Always use the & operator with scanf for basic data types so it knows where to store the input.
Numbers leave \n behind. Use a space before %c in scanf(" %c") to safely skip leftover whitespace.