Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What are printf conversion characters and their types?
In C programming, printf() conversion characters (also called format specifiers) are special codes that tell printf() how to format and display different data types. These characters are preceded by a % symbol and specify the type and format of the variable to be printed.
Syntax
printf("format string with %specifier", variable);
Common Printf Conversion Characters
Here is a list of the most commonly used conversion characters in printf() −
- %d − signed decimal integer
- %u − unsigned decimal integer
- %x − hexadecimal integer (lowercase)
- %X − hexadecimal integer (uppercase)
- %o − octal integer
- %c − single character
- %s − string
- %f − fixed-point decimal floating number
- %e − scientific notation floating point (lowercase)
- %E − scientific notation floating point (uppercase)
- %g − use %f or %e, whichever is shorter
Example: Printf Conversion Characters
The following program demonstrates the usage of various printf conversion characters −
#include <stdio.h>
int main() {
int i = -10;
unsigned int ui = 10;
float x = 3.56f;
double y = 3.52;
char ch = 'z';
char *string_ptr = "TutorialsPoint";
printf("Signed integer: %d<br>", i);
printf("Unsigned integer: %u<br>", ui);
printf("Hexadecimal (lowercase): %x<br>", ui);
printf("Hexadecimal (uppercase): %X<br>", ui);
printf("Octal: %o<br>", ui);
printf("Float: %f<br>", x);
printf("Double: %f<br>", y);
printf("Scientific notation: %e<br>", x);
printf("Compact format: %g<br>", x);
printf("Character: %c<br>", ch);
printf("String: %s<br>", string_ptr);
return 0;
}
Signed integer: -10 Unsigned integer: 10 Hexadecimal (lowercase): a Hexadecimal (uppercase): A Octal: 12 Float: 3.560000 Double: 3.520000 Scientific notation: 3.560000e+00 Compact format: 3.56 Character: z String: TutorialsPoint
Key Points
- Always match the conversion character with the correct data type to avoid undefined behavior.
- Using wrong format specifiers can lead to unexpected output or runtime errors.
- The %g specifier automatically chooses between %f and %e for more compact output.
Conclusion
Printf conversion characters are essential for formatted output in C. Using the correct format specifier ensures proper display of different data types and prevents formatting errors in your programs.
Advertisements
