Nearby lessons
16 of 72C - User Input (scanf)
printf sends values to the screen; scanf reads them back from the keyboard.
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.
In simple words: scanf is the mirror image of printf — printf sends values to the screen, scanf receives them from the keyboard. Same specifiers, same order — but scanf needs a
& 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 & |
Common Mistake: writing
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.
Trainer's Note: The
& (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.
Example01
Calculate Simple Interest
Example02
📝 Key Takeaways
- 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.
🧠 Test Your Knowledge
5 QuestionsProgress: 0 / 5