Step 1 of 5
Read a number
Until now every program printed the same thing each time it ran. To make a program useful, it needs input: data that comes from outside, usually typed by the user. In C, keyboard input arrives on a channel called standard input (stdin), and the easiest way to read from it is scanf.
scanf is the mirror image of printf. It uses the same kind of format string, but instead of printing values, it reads text, converts it, and stores the result in your variables.
#include <stdio.h>
int main(void) {
int age;
scanf("%d", &age);
printf("Next year you'll be %d\n", age + 1);
return 0;
}
29
Next year you'll be 30
Why the &?
printf only needs a variable's value, so you pass age. scanf needs to change the variable, so it needs to know where the variable lives in memory. &age means "the address of age". Think of it as giving scanf the location of the box so it can put the number inside.
Forgetting the & is the most common scanf bug. The compiler warns (format specifies type 'int *' but the argument has type 'int'), and when the program runs, scanf treats the variable's value as an address and writes somewhere it shouldn't. That's undefined behavior: the program may crash, or it may quietly corrupt other data. You'll understand addresses fully in the pointers module; for now, remember: scanf needs & before number and character variables.
Input on this site
Programs here can't pause and wait for you to type. Each test gives the program its input in advance, as if it had been typed. To try your own input, press Run with my input, type into the box, and run.
Your turn: read an int and print it doubled. Input 21 prints 42.