Interactive quiz on C scanf.
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);
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 the output is correct.
scanf("%d", a); // missing &! scanf("%lf", b); // missing &!
scanf needs the address of the variable (prefixed with &). Without the &, scanf treats the variable's value as if it were an address and writes there, causing invalid memory access and most likely a crash.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!
printf("a is %d, b is %f", a, b) output?scanf call reads multiple variables. Note the space between the format specifiers.int a, b; printf("Enter two integers: "); scanf("%d %d", &a, &b); printf("a=%d, b=%d\n", a, b);
3 7 (with a space in between) and presses Enter, what does it print?scanf call can read multiple variables. The format "%d %d" reads two integers separated by whitespace (space, tab, or newline).%d ← first integer 3 → a%d ← next integer 7 → b3 7, 3 7 (many spaces), or even input split across lines all work.
printf, %f works for a double. Does the same apply in scanf?double x; printf("Enter a number: "); scanf("%f", &x); // %f instead of %lf! printf("x = %f\n", x);
3.14 and press Enter, what does it print?printf accepts %f for a double, but scanf requires %lf for a double.%f, scanf writes 4 bytes (assuming a float) to the given address, which only partially fills the 8-byte double → the value is garbage.%f is fine; for scanf, you must use %lf.
int a; scanf("a=%d", &a); // "a=" included in the format printf("a = %d\n", a);
5?"a=%d" says "the input starts with a=, followed by an integer". So a=5 works, but a bare 5 doesn't match the leading a=, and scanf fails to read, leaving a unassigned.%d and %lf.
scanf is called twice to read different types.int age; double height; printf("Age: "); scanf("%d", &age); printf("Height (cm): "); scanf("%lf", &height); printf("%d years, %.1fcm\n", age, height);
25 (Enter) then 170.5 (Enter), what is the output?%d with &int, %lf with &double), you can call scanf back-to-back as many times as you need. Newlines between inputs are handled automatically.%.1f, so the output is 170.5 (rounded to one decimal place), not 170.500000.