Format Specifiers in C
- What are Format Specifiers?
A format specifier tells the compiler what type of data you want to print using the printf() function.
They act like placeholders inside the double quotes ” ” — and are replaced by the variable’s value during output.
Syntax:
printf(“Text %format_specifier”, variableName);
Example:
int myNum = 15;
printf(“%d”, myNum); // Outputs: 15
- Common Format Specifiers
|
Specifier |
Type |
Example |
Output |
|
%d |
Integer (int) |
printf(“%d”, 10); |
10 |
|
%f |
Floating-point (float) |
printf(“%f”, 5.99); |
5.990000 |
|
%c |
Character (char) |
printf(“%c”, ‘A’); |
A |
|
%s |
String (text) |
printf(“%s”, “Hello”); |
Hello |
- Example – Printing Different Types
#include <stdio.h>
int main() {
int myNum = 15; // Integer
float myFloat = 5.99; // Floating number
char myLetter = ‘D’; // Character
printf(“%d\n”, myNum);
printf(“%f\n”, myFloat);
printf(“%c\n”, myLetter);
return 0;
}
✅ Output:
15
5.990000
D
- Combine Text and Variables
You can combine normal text with variable values using commas ,:
Example:
int myNum = 15;
printf(“My favorite number is: %d”, myNum);
✅ Output:
My favorite number is: 15
- Print Multiple Variables Together
You can print different types of data in one line by using multiple format specifiers:
Example:
int myNum = 15;
char myLetter = ‘D’;
printf(“My number is %d and my letter is %c”, myNum, myLetter);
✅ Output:
My number is 15 and my letter is D
- Printing Values Without Variables
You can also print direct values (not stored in variables):
Example:
printf(“My favorite number is: %d”, 15);
printf(“My favorite letter is: %c”, ‘D’);
✅ Output:
My favorite number is: 15My favorite letter is: D
(Tip: Add \n for a new line if needed)
- Formatting Float Values
You can control how many decimal places are shown with %.nf (where n = number of decimals).
Example:
float myFloat = 5.99;
printf(“%.2f”, myFloat); // Outputs 5.99
🧩 Quick Summary
|
Concept |
Description |
Example |
|
Format Specifier |
Tells C which data type to print |
%d, %f, %c, %s |
|
Combine text & variable |
“My number is %d”, num |
✅ |
|
Print multiple types |
“Age: %d, Grade: %c”, age, grade |
✅ |
|
Float precision |
“%.2f”, value |
✅ |