Module 2 · Variables, Types, Input and Operators — topic 4 of 6
Input and Output
printf formats output with conversion specifiers, widths and precision; scanf reads typed values into variables through their addresses. Learn both, and how to read input safely.
Learning objectives
- Use printf conversion specifiers, field widths and precision
- Read numbers, characters and words with scanf
- Check scanf's return value and avoid common input bugs
Definition
Formatted I/O in C is provided by<stdio.h>:printfconverts values to text according to a format string and writes them to standard output, andscanfreads text from standard input, converts it according to a format string, and stores the results through pointer arguments.
Introduction
Interactive programs need to talk to the user. In C, printf does the talking and scanf does the listening. Both are driven by a format string full of % conversion specifiers that say what type each value is.
Input is where many beginner C programs break: a missing &, a stray newline left in the input buffer, or a user typing letters where a number is expected. This lesson covers the rules that avoid those problems.
Why it matters
Correctly formatted output — aligned columns, fixed decimals — is expected in every lab assignment and in real reports.
Robust input handling separates programs that work in a demo from programs that survive real users.
Detailed explanation
A field width pads output: %5d right-aligns in 5 columns, %-5d left-aligns. Precision after a dot sets decimal places for %f (%.3f) or maximum characters for %s (%.3s).
scanf needs the address of each variable so it can store into it: scanf("%d", &age);. Arrays such as char name[20] already decay to an address, so no & is used with %s.
In scanf, %f reads a float and %lf reads a double (in printf, %f works for both). %s reads one whitespace-delimited word; give it a width (%19s) to avoid overflowing the array.
scanf returns the number of items successfully converted. Checking it is the simplest way to detect bad input. Most specifiers skip leading whitespace, but %c does not — write " %c" with a leading space to skip a leftover newline.
Syntax
- The number and types of arguments must match the specifiers exactly.
&gives the address of a variable; it is required inscanfbut not inprintf.scanfreturns how many values it stored, orEOFat end of input.
Code examples
Formatting output
[ 3] [3 ] [49.50] [ 148.5] Discount: 10%
Reading two numbers
12 30
Enter two integers: Sum = 42
The user's typing is not part of the program's output; the sample input is shown separately.
More examples
Validating input with the return value
19 B
Age: Grade (A-F): Age 19, grade B
Step-by-step explanation
scanf("%d", &age)returns 1 when it stores an integer; anything else means the input was not a number, so the program stops with status 1.- After reading 19, the newline the user pressed is still waiting in the input buffer.
" %c"— note the space — skips that newline and any spaces before reading the grade character.- Without the space,
%cwould read the newline itself andgradewould not be 'B'.
Expected output
Running “Validating input with the return value” with the sample input shown prints exactly:
Practical applications
- Command-line tools print aligned tables with width specifiers.
- Log files use fixed formats such as
%04d-%02d-%02dfor dates. - Competitive programming judges feed input through standard input exactly as in these examples.
Best practices
- Always check what
scanfreturns. - Give every
%sa width one less than the array size. - Prompt the user clearly and print a newline at the end of every output line.
Common mistakes
Forgetting & in scanf
Avoid
Prefer
scanf receives the value of n instead of its address and writes to a random location — undefined behaviour, often a crash.
Using %f to read a double
Avoid
Prefer
%f tells scanf it has a float *; writing 4 bytes into an 8-byte double produces nonsense.
Using gets()
Avoid
Prefer
gets cannot limit input length and was removed from C11. fgets stops at the buffer size.
Important notes
- Standard output is usually line-buffered: text without a trailing
\nmay appear late.fflush(stdout)forces it out. fflush(stdin)is undefined behaviour in standard C; skip leftover characters by reading them instead.
Key takeaways
printfformats values; specifiers must match argument types.scanfneeds addresses (&var) and returns how many items it read.%lfreads a double;" %c"skips whitespace before a character.
Try it yourself
- 1Read a student's name (one word) and three marks, and print the name and average to two decimals.
Show hint
Use
%19sfor the name and%dthree times. - 2Print a 3-row table of item, quantity and price with aligned columns using field widths.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
10 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is wrong with `scanf("%d", n);` where n is an int?
- BeginnerWhat is printed?
- BeginnerWhat is printed?