C Format Specifiers

C Format Specifiers
In C language, format specifiers tell functions like printf() and scanf() how to interpret and display data.
They are essential for correct input/output, exams, and interviews.
What Are Format Specifiers?
A format specifier is a special sequence (starting with
%) used in formatted I/O to specify the data type.
Most Common Format Specifiers
Integer Types
| Data Type | Specifier | Example |
|---|---|---|
int | %d or %i | printf("%d", a); |
short int | %hd | printf("%hd", s); |
long int | %ld | printf("%ld", l); |
long long int | %lld | printf("%lld", ll); |
unsigned int | %u | printf("%u", u); |
unsigned long | %lu | printf("%lu", ul); |
unsigned long long | %llu | printf("%llu", ull); |
Floating-Point Types
| Data Type | printf() | scanf() |
|---|---|---|
float | %f | %f |
double | %f | %lf |
long double | %Lf | %Lf |
Character & String Types
| Data Type | Specifier | Example |
|---|---|---|
char | %c | printf("%c", ch); |
char[] (string) | %s | printf("%s", str); |
- For
scanf("%s"), no&is needed because arrays already give addresses.
Special & Advanced Specifiers
| Purpose | Specifier | Example |
|---|---|---|
| Pointer address | %p | printf("%p", ptr); |
| Octal | %o | printf("%o", n); |
| Hex (lower) | %x | printf("%x", n); |
| Hex (upper) | %X | printf("%X", n); |
| Scientific | %e / %E | printf("%e", d); |
| General format | %g / %G | printf("%g", d); |
Print % | %% | printf("%%"); |
Width & Precision (Very Important)
Width
Precision (Decimals)
Width + Precision
Format Specifiers in scanf()
- Always use
&for variables - Except arrays/strings
printf() vs scanf() Specifier Differences
| Type | printf() | scanf() |
|---|---|---|
int | %d | %d |
float | %f | %f |
double | %f | %lf |
char | %c | %c |
| string | %s | %s |
Common Mistakes
- Using
%dforfloat Using%ffordoubleinscanf()Forgetting&inscanf()Using%sfor a singlecharMismatch between variable type & specifier
Interview Questions (Must Prepare)
Difference between
%dand%iWhy
%lfis used fordoubleinscanf()?What is
%pused for?How to print 2 decimal places?
What happens if format specifier mismatches type?
Summary
- Format specifiers define how data is read & printed
-
%d,%f,%c,%sare most common scanf()needs address (&)- Precision and width control output format
- Critical for correct I/O, exams & interviews
