C Format Specifiers
1. What are Format Specifiers?
-
Format specifiers tell C what type of data to print or read.
-
Used in functions like
printf()(output) andscanf()(input). -
They are placeholders that start with
%.
2. Common Format Specifiers
| Specifier | Data Type | Example |
|---|---|---|
%d |
int (integer) | int age = 25; |
%i |
int (integer) | int num = 10; |
%f |
float | float pi = 3.14; |
%lf |
double | double d = 3.14159; |
%c |
char (character) | char ch = ‘A’; |
%s |
string | char name[] = “Vipul”; |
%u |
unsigned int | unsigned int u = 100; |
%x |
hexadecimal | int x = 255; |
%o |
octal | int o = 8; |
%% |
percent symbol | printf(“%%”); prints % |
3. Using Format Specifiers with printf()
Example 1: Printing different types
Output:
-
%.1f→ Limits float output to 1 decimal place.
4. Using Format Specifiers with scanf()
Example 2: Reading user input
Explanation:
-
&→ Passes the address of the variable toscanf(). -
" %c"→ Space avoids reading leftover newline characters.
5. Tips and Tricks
-
Always match the format specifier with the variable type.
-
Use
%.nfto control decimal precision. -
Use
%%to print the%symbol. -
%sautomatically stops reading input at space. For full sentences, usegets()(though unsafe) orfgets().
