Skip to content
FollowtheDamnCode

Taking Input with scanf

Reading numbers the user types.

3 minute read

Big idea

scanf reads what the user types and stores it in a variable.

The idea

It looks like printf, but works the other way — input instead of output:

int age;
scanf("%d", &age);
  • "%d" — "expect a whole number".
  • &age — "put it in age". The & means address of: scanf needs to know where age lives so it can fill it.

Example

Try it — edit it and run it again
#include <stdio.h>

int main(void) {
    int a, b;
    scanf("%d %d", &a, &b);
    printf("%d\n", a + b);
    return 0;
}
input
3 4
output
7

Run and edit it in the app.

Watch it

Think of it like

Giving a delivery driver your home address. &age is the address, so scanf knows exactly which box to drop the number into.

🕷️ Spidey-sense: Even heroes have to listen. scanf waits for the user to type, then drops the value into your variable. Always hand it the address with & — like a delivery, it needs to know where to drop it.

Common mistake

Forgetting the &. The program compiles, but crashes or reads garbage — it goes full "Mr. Stark, I don't feel so good…" and falls apart.

scanf("%d", age);    // ✗
scanf("%d", &age);   // ✓

Key terms

  • Input — Data the user gives your program.
  • scanf — Reads input into variables.
  • & — "Address of" — tells scanf where to store the value.

Check yourself

What does scanf do?

Why is there an & in scanf("%d", &n)?

What's the most common scanf mistake?