Lesson 6 of 7 · C Foundations · 2 min read · Updated
Reading input with scanf
Make the program ask, and respond to what it is told.
A program that always prints the same thing is not much use. scanf reads what the user types and puts it into a variable.
#include <stdio.h>
int main(void)
{
int age;
printf("How old are you? ");
scanf("%d", &age);
printf("In ten years you will be %d.\n", age + 10);
return 0;
}
How old are you? 25
In ten years you will be 35.
That & is not a typo
scanf needs to put a value into your variable, so it needs to know where that variable lives. The & means "the address of". Without it, scanf receives a copy of the value and writes to a random place instead.
This is the single most common mistake with scanf, and it is worth remembering now: printf takes the value, scanf takes the address.
Warning
Forgetting the & usually compiles with only a warning, then crashes when you run it. Read compiler warnings — they are usually right.
Reading more than one value
int width, height;
printf("Width and height: ");
scanf("%d %d", &width, &height);
printf("Area: %d\n", width * height);
Note
scanf returns how many values it successfully read. Checking that return value is how a careful program notices the user typed letters where a number was expected.
Why does scanf("%d", &age) need the &?
Create a free account to save your progress, or sign in.