01. Formatted Output with printf
🟢 Difficulty: Beginner | Format Specifiers, Width, Precision & Return Values
📖 Definition
The printf() function (declared in <stdio.h>) writes formatted text to standard output (stdout). It accepts a format string containing plain characters and conversion specifications beginning with %, followed by matching arguments to format and print.
🎯 Why It Is Used
- Formatted Data Presentation: Displays floating-point values with controlled decimal precision, left-aligned columns, or leading zeros.
- System Diagnostics: Prints memory addresses using
%pand buffer byte counts using%zu. - Character Escape Sequences: Embeds tabs (
\t), newlines (\n), quotes (\"), and backslashes (\\).
⚙️ How It Works
printf() returns the total number of characters printed on success, or a negative value if an output error occurs. The general syntax of a format specifier is:
%[flags][width][.precision][length_modifier]specifier
📝 Format Specifiers & Escape Sequences
| Specifier | Target Data Type | Description & Example |
|---|---|---|
%d / %i | int | Signed decimal integer |
%u | unsigned int | Unsigned decimal integer |
%x / %X | unsigned int | Unsigned hexadecimal integer (lowercase / uppercase) |
%f / %lf | float / double | Decimal floating point (default 6 decimal digits) |
%e / %E | double | Scientific exponential notation |
%c | char | Single character |
%s | char* | Null-terminated character string |
%p | void* | Pointer memory address (requires (void*) cast) |
%zu | size_t | Unsigned size returned by sizeof |
%% | Literal % | Prints a literal percent sign |
🔀 Alignment & Padding Flags
%-10s: Left-aligns a string within a field width of 10 characters.%08d: Pads an integer with leading zeros to guarantee 8 digits width (e.g.00000042).%+.2f: Always displays explicit+or-sign for floating-point values.
🌱 Beginner Example
#include <stdio.h>
int main(void) {
int age = 25;
double gpa = 3.854;
char name[] = "Alice";
printf("Name: %s | Age: %d | GPA: %.2f\n", name, age, gpa);
return 0;
}
🌼 Intermediate Example: Formatted Financial Report Table
#include <stdio.h>
int main(void) {
printf("%-15s %-10s %12s\n", "ITEM", "CATEGORY", "PRICE ($)");
printf("-----------------------------------------\n");
printf("%-15s %-10s %12.2f\n", "Laptop", "Electronics", 1299.99);
printf("%-15s %-10s %12.2f\n", "Desk Chair", "Furniture", 249.50);
printf("%-15s %-10s %12.2f\n", "Coffee Mug", "Kitchen", 12.00);
printf("-----------------------------------------\n");
return 0;
}
🌲 Advanced Example: Checking printf Return Value & Pointer Formatting
#include <stdio.h>
int main(void) {
int value = 0x42;
int *ptr = &value;
int chars_printed = printf("Value: %d (0x%04X) at Address: %p\n", value, value, (void*)ptr);
printf("Previous line printed exactly %d characters to stdout.\n", chars_printed);
return 0;
}
🔍 Line-by-Line Explanation
%-15s: Specifies a left-justified string field of 15 characters width.%12.2f: Specifies a right-justified float field of 12 total characters, displaying exactly 2 decimal places.0x%04X: Formats integer in uppercase hexadecimal, padded with leading zeros to 4 digits width.(void*)ptr: Casts pointer tovoid*to comply with ISO C standard for%pspecifier.int chars_printed = printf(...): Stores total characters printed to standard output.
💻 Expected Terminal Output
ITEM CATEGORY PRICE ($)
-----------------------------------------
Laptop Electronics 1299.99
Desk Chair Furniture 249.50
Coffee Mug Kitchen 12.00
-----------------------------------------
Value: 66 (0x0042) at Address: 0x7ffdb128448c
Previous line printed exactly 46 characters to stdout.
⚠️ Common Mistakes & Pitfalls
- Mismatched Format Specifiers: Printing a
doublewith%dproduces garbage data or segmentation fault. - Passing Pointers without
(void*)cast: Usingprintf("%p", ptr)without(void*)ptrcast triggers compiler warnings. - Missing Arguments: Providing specifiers without passing corresponding variable arguments cause undefined behavior.
📌 Important Rules & Limitations
- Format specifiers are processed sequentially from left to right.
- In
printf(),floatarguments are automatically promoted todouble(so%fhandles both).
🌐 Multilingual Explanation: English
printf() writes formatted output to standard output. It uses format specifiers (%d, %f, %s, %p, %zu) along with width and precision flags to control visual formatting and table column alignment.
🌐 Multilingual Explanation: Hindi (Roman Script)
printf() terminal par text dikhane ke liye use hota hai. Format specifiers (%d, %f, %s, %p, %zu) batate hain ki kis type ka data print karna hai. Floating numbers ke decimal places ko %.2f se control kiya ja sakta hai.
🌐 Multilingual Explanation: Marathi (Roman Script)
printf() ne formatted output screen var print hotat. %d integers sathi, %.2f decimal places sathi aani %zu memory size sathi vapartat.
❓ Practice Questions
- What value does
printf()return? - How do you format a floating-point number to display exactly 3 decimal places?
- Why must pointers be explicitly cast to
(void*)when using%pinprintf()?
🚀 Practical Coding Challenge
Write a C program named receipt_formatter.c that formats a store receipt containing three items with quantities, unit prices, and subtotal. Format the output into neatly aligned columns with $ symbols and 2 decimal places using printf() alignment flags.