Skip to content

Reading input with scanf

Read · 1 of 5

scanf fills a variable for you

scanf("%d", &age); waits for a whole number and stores it in age. The & gives scanf the address of age, so it knows where to put the value. Forgetting it is the classic C bug.

Read several values at once with scanf("%d %d", &a, &b);. Spaces and new lines between the numbers don't matter. Use %lf to read a double.

Read this lesson as text

Read whole numbers and decimals typed by the user.

scanf fills a variable for you

scanf("%d", &age); waits for a whole number and stores it in age. The & gives scanf the address of age, so it knows where to put the value. Forgetting it is the classic C bug.

Read several values at once with scanf("%d %d", &a, &b);. Spaces and new lines between the numbers don't matter. Use %lf to read a double.

Watch input arrive

#include <stdio.h>

int main() {
    int a, b;
    scanf("%d %d", &a, &b);
    printf("%d + %d = %d\n", a, b, a + b);
    return 0;
}
  1. Line 4: Two int boxes, not filled yet.
  2. Line 5: The input is "7 5": the first number goes into a, the second into b.
  3. Line 6: Now we use them like any variable.

Decimals in, decimals out

#include <stdio.h>

int main() {
    double km;
    scanf("%lf", &km);
    printf("%.1f m\n", km * 1000);
    return 0;
}

The user types 2.5. What does this print?

  • 2500.0 m
  • 2500 m
  • 2.5 m
Show the answer

2500.0 m %lf reads 2.5 into the double; times 1000 is 2500, printed with one decimal place.

Exercise: Add two numbers

Read two whole numbers and print their sum.

Exercise: Area of a circle

Read the radius (a decimal) and print the area, using 3.14159 for π, with 2 decimals.