When using printf() in C, you'll often see things like \n, %d, and %f.
They may look confusing at first, but they're actually pretty simple. Escape sequences control how text is displayed, while format specifiers tell C what type of value we're working with.
Escape Sequences
An escape sequence is a combination of characters beginning with a backslash (\) that represents a special character or action.
For example:
printf("Hello\nWorld");
Output:
Hello
World
Here, \n means new line.
Common Escape Sequences
Escape Sequence | Meaning | Example |
|---|---|---|
| New line |
|
| Tab space |
|
| Backslash |
|
| Double quote |
|
| Single quote |
|
| Null character | Used to terminate strings |
For example:
printf("Name:\tJohn\nAge:\t20");
Output:
Name: John
Age: 20
Format Specifiers
A format specifier is a special symbol used with functions like printf() and scanf() to indicate the type of data being displayed or read.
For example:
int age = 20;
printf("Age = %d", age);
Here, %d tells printf() that age is an integer.
Common Format Specifiers
Specifier | Used For | Example |
|---|---|---|
| Integer |
|
| Floating-point value |
|
|
|
|
| Character |
|
| String |
|
| Unsigned integer |
|
| Hexadecimal integer |
|
For example:
int age = 20;
float height = 5.8;
char grade = 'A';
printf("Age: %d\n", age);
printf("Height: %f\n", height);
printf("Grade: %c\n", grade);
Output:
Age: 20
Height: 5.800000
Grade: A
Escape Sequence vs Format Specifier
These two are easy to confuse, so remember the difference:
Escape Sequence | Format Specifier |
|---|---|
Usually starts with | Starts with |
Controls special characters/actions | Represents a data type |
Example: | Example: |
Used mainly inside strings/character constants | Used with formatted input/output |
Simple Example
int age = 20;
printf("Hello\nAge = %d", age);
Here:
\n→ moves to a new line%d→ displays the integerage
Output:
Hello
Age = 20
In Simple Words
Escape sequences control how text is displayed, while format specifiers tell C what type of data to read or display.
The easiest way to remember them is:
\ → Special character/action
% → Data format