C Format Specifiers

In this tutorial, you will learn various format specifiers used in the C programming language with the help of examples.


The format specifiers are used for formatted input and output in the C programming language. It is the method to tell the compiler what types of data a variable is holding during taking input using scanf() function and printing using printf() function. The format specifiers always start with a '%' character. Some of the examples are '%d', '%c', etc.

Following is the list of some of the most commonly used format specifiers.

Format Specifier Description
%d or %i Signed integer. The variable can hold both the positive and negetive numbers.
%u Unsigned int. The variable can hold only the positive value.
%c Character
%s String
%e or %E Scientific notation of floats. It is also known as Mantissa or Exponent.
%f Float values. By default, it prints the 6 values after ‘.’.
%g or %G Similar as %e or %E
%hi Signed integer (short)
%hu Unsigned Integer (short)
%l or %ld or %li Long
%lf Double
%Lf Long double
%lu Unsigned int or unsigned long
%lli or %lld Long long
%llu Unsigned long long
%o Octal representation
%p Pointer
%x or %X Hexadecimal representation
%n Prints nothing
%% Prints % character

We can also some parts with the format specifiers. They are as below:

  • A minus symbol (-) sign tells left alignment.
  • A number after % specifies the minimum field width. If a string is less than the width, it will be filled with spaces.
  • A period (.) is used to separate field width and precision.

Let’s check an example that covers most of the format specifiers mentioned above.

Example

#include <stdio.h>
void main() {
//printing character data with %c
char ch = 'A';
printf("%c\n", ch);

//print decimal or integer data with d and i
int x = -10, y = 20;
printf("%d\n", x);
printf("%u\n", y);

float f = 15.43;
printf("%f\n", f); //printing float value
printf("%e\n", f); //printing in scientific notation

int a = 56;
printf("%o\n", a); //printing in octal format
printf("%x\n", a); //printing in hex format

char str[] = "Hello World";
printf("%s\n", str); //printing string data
printf("%15s\n", str); //shift to the right 15 characters including the string
printf("%-10s\n", str); //left align
printf("%15.5s\n", str); //shift to the right 15 characters including the string, and print string up to 5 character
printf("%-15.5s\n", str); //left align and print string up to 5 character
}

Output

A
-10
20
15.430000
1.543000e+001
70
38
Hello World
Hello World
Hello World
Hello
Hello
The format specifiers also work in the same manner with the scanf() function. The scanf() function takes the input from the standard input device and stores it in the variable as per the specified format.

Please get connected & share!

Advertisement