C Format Specifiers: Beginner-Friendly Guide
In C programming, format specifiers are used to tell the compiler the type of data to expect for input or output. They are mainly used with functions like printf()
and scanf()
.
Let’s break it down step-by-step.
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
List of Common Format Specifiers in C
Format Specifier | Data Type | Example Value | Used With |
---|---|---|---|
%d or %i | int | 10 | printf , scanf |
%f | float | 3.14 | printf , scanf |
%lf | double | 10.89 | scanf only |
%c | char | ‘A’ | printf , scanf |
%s | string | “Hello” | printf , scanf |
%u | unsigned int | 30000 | printf , scanf |
%ld | long int | 123456L | printf , scanf |
%lu | unsigned long | 123456UL | printf , scanf |
%x / %X | hex int | 0x1A | printf |
%o | octal int | 075 | printf |
%% | Literal % | % | printf |
Example: Using Format Specifiers with printf()
#include <stdio.h>
int main() {
int age = 25;
float pi = 3.1415;
char grade = 'A';
char name[] = "Alex";
printf("Name: %s\n", name);
printf("Age: %d\n", age);
printf("PI: %.2f\n", pi); // 2 decimal places
printf("Grade: %c\n", grade);
return 0;
}
✅ Output:
Name: Alex Age: 25 PI: 3.14 Grade: A
Example: Using Format Specifiers with scanf()
#include <stdio.h>
int main() {
int age;
float height;
char name[30];
printf("Enter your name: ");
scanf("%s", name);
printf("Enter your age and height: ");
scanf("%d %f", &age, &height);
printf("Hello %s, age: %d, height: %.1f\n", name, age, height);
return 0;
}
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 to Avoid
Mistake | What Happens |
---|---|
Using wrong format specifier | Garbage value or program crash |
Forgetting & in scanf() | Runtime error or wrong input |
Mismatched types | Unexpected behavior |
Printing float with %d | Incorrect output |
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" |