🇯🇵 日本語 | 🇺🇸 English
Advertisement

Quiz (scanf)

Interactive quiz on C scanf.

Question 1 — scanf basics

int a;
double b;
printf("Enter a: ");
scanf("%d", &a);
printf("Enter b: ");
scanf("%lf", &b);
printf("a is %d, b is %f \n", a, b);
Suppose you enter 5 for a and 3 for b. What gets printed?

What does this print?

a is 5, b is 3.000000
a is 5, b is 3
a is 5.000000, b is 3.000000
Explanation: a is an int printed with %d → 5. b is a double printed with %f → 3.000000 (%f defaults to 6 decimal places). Both format specifiers match their types, so output is correct.

Question 2 — What if you forget &?

scanf("%d", a);   // missing &!
scanf("%lf", b);  // missing &!

What happens?

Runs normally
Crashes as soon as input is received
Prints 0
Explanation: scanf requires the address of the variable (prefixed with &). Without &, scanf treats the variable's value as an address and writes there, causing invalid memory access and likely a crash.
Always prefix scanf arguments with & for scalar types!

Question 3 — Wrong type in scanf

An int a is read with %lf, and a double b is read with %d.
int a;
double b;
scanf("%lf", &a);  // %lf for int!
scanf("%d", &b);   // %d for double!
If you enter 3 for a and 5 for b, what does printf("a is %d, b is %f", a, b) output?

What does this print?

a is 3, b is 5.000000
a is 0, b is 0.000000 (no correct value)
Compile error
Explanation: When scanf's format doesn't match the target variable's type, the write size is wrong and the variable is not correctly populated. Output varies by platform but it won't be what you expected.
In scanf, use %d for integers and %lf for doubles.
Advertisement

Related lessons

Introduction
printf & scanf
How to use printf and scanf in C. Format specifier reference.
Introduction
Quiz (Variables & printf)
Interactive quiz on C variables and printf.
Introduction
Variables
What are C variables? Visual guide to int, double, and char.
← Previous lesson
Quiz (Variables & printf)
Next lesson →
Arithmetic operators