In C programming, formatting specifiers are used to control the appearance of output when you use functions like printf
. These specifiers allow you to format and display data in a specific way, such as specifying the width of a field, the number of decimal places for floating-point numbers, and more. Here’s an overview of commonly used formatting specifiers:
- Integer Formatting Specifiers:
%d
: Format as a signed decimal integer.%u
: Format as an unsigned decimal integer.%x
or%X
: Format as a hexadecimal integer (lowercase or uppercase).%o
: Format as an octal integer.
Example:
int num = 42;
printf("Decimal: %d, Hexadecimal: %x, Octal: %o\n", num, num, num);
Output:
Decimal: 42, Hexadecimal: 2a, Octal: 52
- Floating-Point Formatting Specifiers:
%f
: Format as a floating-point number (default precision: 6 decimal places).%.nf
: Format withn
decimal places (replacen
with the desired number).%e
or%E
: Format in scientific notation (lowercase or uppercase).
Example:
float pi = 3.14159265359;
printf("Default: %f, 2 Decimal Places: %.2f, Scientific: %e\n", pi, pi, pi);
Output:
Default: 3.141593, 2 Decimal Places: 3.14, Scientific: 3.141593e+00
- Character Formatting Specifiers:
%c
: Format as a character.%s
: Format as a string.
Example:
char letter = 'A';
char name[] = "John";
printf("Character: %c, String: %s\n", letter, name);
Output:
Character: A, String: John
- Width and Alignment Specifiers:
%Ns
: Format with a minimum field width ofN
(right-aligned by default).%-Ns
: Left-align within a field of widthN
.
Example:
int num = 42;
printf("Width 5: %5d, Left-aligned: %-5d\n", num, num);
Output:
Width 5: 42, Left-aligned: 42
- Pad with Zeros:
%0Ns
: Pad with leading zeros instead of spaces.
Example:
int num = 42;
printf("Zero-padded: %05d\n", num);
Output:
Zero-padded: 00042
- Printing Special Characters:
%%
: To print a literal ‘%’ character.
Example:
printf("The percentage symbol: %%\n");
Output:
The percentage symbol: %
These are some of the commonly used formatting specifiers in C. You can combine them and use them creatively to format your output as per your requirements. Keep in mind that precision and width can be adjusted using .
and N
, respectively, as shown in the examples.
PATRONIZE US BUY DOMAIN DONATE TO BIONUGGETS ($) DONATE TO BIONUGGETS (₦)