Nearby lessons
23 of 124C - User Input (scanf)
printf sends values to the screen; scanf reads them back from the keyboard. This lesson covers scanf and the & that beginners always forget, reading single characters with getchar and putchar, and finishes with a complete program that takes three numbers and calculates simple interest.
scanf() — Taking Input
scanf("specifiers", &variables...) reads input from the keyboard. Important: you must put & before a variable (except for strings) so scanf knows where to store the value.
& before every variable (except strings).
| Goal | printf | scanf |
|---|---|---|
| An integer | printf("%d", age) |
scanf("%d", &age) |
| A float | printf("%f", pay) |
scanf("%f", &pay) |
| A character | printf("%c", ch) |
scanf("%c", &ch) |
| A string | printf("%s", name) |
scanf("%s", name) — no & |
scanf("%d", age) without the &. The program still compiles, then either stores the value in a random place or crashes. If your input "does not work", check for a missing & first.
& (address of) operator is essential in scanf: scanf("%d", &age) stores the input at age's memory location. Strings are the one exception — an array name already is an address, so %s takes no &. This will make full sense after the Pointers chapter.
Reading and Writing Single Characters
When you only need one character, scanf is more machinery than you need:
getchar()— reads one character from the keyboard.putchar(c)— prints one character.
getchar and putchar are the single-character versions of scanf and printf. No format string, no & — just one character in, one character out.
getch() and getche() (from conio.h) — but those are Windows-only functions and not part of standard C. Modern practice is to use getchar() (standard) or the safer fgets() for strings, which we see in Chapter 8.
A Complete Example — Calculate Simple Interest
This program puts the whole chapter together: it declares variables, reads three values with one scanf, calculates, and prints the result to two decimals.
One scanf can read several values at once — "%f %f %f" reads three floats, and the user separates them with spaces or newlines. Notice each variable still gets its own &.
float p, r, t, si;), input (scanf), process (si = ...), output (printf). Almost every C program you write will follow this shape.
- printf() outputs; scanf() inputs (from stdio.h).
- Format specifiers: %d int, %f float, %.2f two decimals, %c char, %s string.
- Escape sequences: \n new line, \t tab, \\ backslash, %% percent.
- scanf needs & before variables (except strings).
- getchar()/putchar() handle one character.
- getch/getche are Windows-only; prefer standard getchar.