Input and Output: printf() and scanf()
Interacting with terminal users in C relies on standard library formatted I/O functions.
What is it?
`printf()` (print formatted) sends formatted output to standard output (console). `scanf()` (scan formatted) reads formatted data from standard input (keyboard).
Why is it used?
Essential for building command-line utilities, student grade inputs, calculators, and interactive menu drivers.
Detailed Explanation
Format Specifiers:
• `%d` or `%i`: Signed decimal integer
• `%u`: Unsigned integer
• `%f`: Float
• `%lf`: Double (long float)
• `%c`: Single character
• `%s`: String (reads up to first whitespace!)
The Address-Of (`&`) Operator in `scanf()`:
`scanf()` requires the memory address where it should store the typed data. For primitive variables (`int`, `float`, `char`), you MUST prepend the variable name with `&` (e.g. `scanf("%d", &age);`).
Syntax Structure
Syntax Blueprint
printf("Format string: %d\n", variable);
scanf("%d", &variable); // Note & address-of
Code Example
C Code
#include <stdio.h>
int main() {
int student_id = 101;
float exam_percentage = 88.5f;
char attendance_grade = 'A';
// Formatted output demonstrations
printf("=== Student Enrollment Record ===\n");
printf("Roll Number: [%05d]\n", student_id); // Padded to 5 digits with zeros
printf("Percentage: [%.2f%%]\n", exam_percentage); // 2 decimal places with literal %
printf("Attendance: [%-10c]\n", attendance_grade); // Left aligned in 10-char width
return 0;
}
Explanation of the Code
• `%05d` pads the integer with leading zeros to 5 total digits (`00101`).
• `%%` prints a literal percent sign `%` in `printf`.
• `%-10c` left-aligns the character in a 10-character wide column.
Expected Output
=== Student Enrollment Record ===
Roll Number: [00101]
Percentage: [88.50%]
Attendance: [A ]
Real-World Application
Used across Linux utilities, compiler CLI flags, and embedded system debugging serial consoles.
Common Mistakes to Avoid
• Omitting `&` in `scanf("%d", age)`—the #1 source of segmentation faults (crashes) for beginners in C!
• Buffer overflow when using `scanf("%s", str)` with strings larger than array size.
Quick Practice Challenge
Print the number 42 padded with zeros to 6 digits using `printf`.
Key Takeaways
• Use `printf()` with format specifiers `%d`, `%f`, `%c`, `%s`.
• `scanf()` requires memory addresses; prepend primitives with `&`.
• Use `%%` to print a literal percent symbol in `printf`.