C Format Specifiers: Beginner-Friendly Guide
Format specifiers in C tell the compiler what type of data to expect when printing or scanning values using printf()
and scanf()
functions.
They ensure that the correct data type is formatted properly.
Why Are Format Specifiers Important?
When you use printf()
or scanf()
, the format specifier helps match the variable type so that the value is displayed or read correctly.
What Are Format Specifiers?
A format specifier starts with a percent sign %
followed by a character that represents the data type.
Used in:
printf()
– to display valuesscanf()
– to receive input from users
Format Specifiers with Examples in C
Format Specifier | Data Type | Used With | Example Output |
---|---|---|---|
%d | int | printf , scanf | 10 |
%f | float | printf , scanf | 10.500000 |
%c | char | printf , scanf | A |
%s | string (char array) | printf , scanf | Hello |
%lf | double | printf , scanf | 12.345678 |
%u | unsigned int | printf | 4294967295 |
%x / %X | hexadecimal | printf | a / A |
%o | octal | printf | 12 (octal of 10) |
%p | memory address | printf | 0x7ffee3ac4c90 |
%% | percentage sign | printf | % |
Example: Using %d, %f, %c
#include <stdio.h>
int main() {
int age = 25;
float height = 5.9;
char grade = 'A';
printf("Age: %d\n", age);
printf("Height: %f\n", height);
printf("Grade: %c\n", grade);
return 0;
}
Output:
Age: 25
Height: 5.900000
Grade: API: 3.14
Example: Using %s and %lf
#include <stdio.h>
int main() {
char name[] = "Alice";
double balance = 12345.67;
printf("Name: %s\n", name);
printf("Balance: %lf\n", balance);
return 0;
}
Field Width and Precision
Format | Meaning |
---|---|
%10d | Print integer in 10-width field |
%.2f | Print float with 2 decimals |
%10.3f | Float: width 10, 3 decimal places |
printf("%10.2f", 123.456); // Output: " 123.46"
scanf() and Format Specifiers
int num;
float rate;
char letter;
scanf("%d %f %c", &num, &rate, &letter);
Tips for Accurate Usage
Always use
&
withscanf()
variables (except for arrays/strings).Match the specifier to the correct data type.
Use
.2f
or.1f
for limiting decimal places in floats/doubles.scanf("%s", name)
doesn’t need&
because arrays decay to pointers.
Common Mistakes
Mistake | Problem |
---|---|
Using wrong specifier | Garbage output or compiler warning |
Forgetting & in scanf() | Causes runtime errors |
Mismatched data type | May crash or behave unexpectedly |
Formatting Tricks
Format | Purpose | Example |
---|---|---|
%.2f | Print 2 decimal places | 3.14 |
%5d | Print integer in 5-character space | " 25" |
%-5d | Left-align in 5-character space | "25 " |
%02d | Print integer padded with zeros | "07" |
Best Practices
Tip | Why It’s Important |
---|---|
Use the correct format for the data | Ensures correct output and memory usage |
Use precision for floating values | Improves readability |
Always test input/output | Prevents bugs during runtime |