You’ve already seen in previous tutorial some characters in printf() starts with “%” sign. So, what does that sign mean? What is the purpose of these characters?

Characters starts with “%” sign in C known as format specifier. The purpose of these special characters is to define the format of a variable in which it’ll be printed on stdout (standard output) or file. They help the compiler to understand the data type of a variable. Standard syntax of a format specifier is given below

%[flags][width][.precision][length]specifier

Note: for the time being ignore flags, width, .precision and length we’ll discuss them later.

Below is the table of different format specifiers used in C.

SpecifierOutputExample
d or iSigned decimal integer392
uUnsigned decimal integer7235
oUnsigned octal610
xUnsigned hexadecimal integer7fa
XUnsigned hexadecimal integer (uppercase)7FA
fDecimal floating point, lowercase392.65
FDecimal floating point, uppercase392.65
eScientific notation (mantissa/exponent), lowercase3.9265e+2
EScientific notation (mantissa/exponent), uppercase3.9265E+2
gUse the shortest representation: %e or %f392.65
GUse the shortest representation: %E or %F392.65
aHexadecimal floating point, lowercase-0xc.90fep-2
AHexadecimal floating point, uppercase-0XC.90FEP-2
cCharactera
sString of characterssample
pPointer addressb8000000
nNothing printed.
The corresponding argument must be a pointer to a signed int.
The number of characters written so far is stored in the pointed location.
%A % followed by another % character will write a single % to the stream.%

Source: cplusplus.com

flags, width, .precision and length are called sub specifiers. They are used to format the output and they are optional.

flags: they are used to format the output like justifying, show (+, -) sign with a number or show (0) instead of spaces.

width: used to limit the number of characters to be printed on screen.

.precision: used with float or double to limit the number of digits after decimal point.

length: used to define the length of a data type. It varies from data type to data type.

Example

#include <stdio.h>
#include <conio.h>

/* Format Specifier Example - bytesik.com */

void main() {
   printf ("Characters: %c %c \n", 'a', 65);
   printf ("Decimals: %d %ld\n", 1977, 650000L);
   printf ("Preceding with blanks: %10d \n", 1977);
   printf ("Preceding with zeros: %010d \n", 1977);
   printf ("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
   printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
   printf ("Width trick: %*d \n", 5, 10);
   printf ("%s \n", "A string");
   getche();
}