How to Use Format Specifiers in C

What is Format Specifier in C?

In C, format specifiers are placeholders within a format string and they are used with functions like printf() and scanf() to specify the type and format of the data to be printed or read.

Format specifiers begin with a percent sign (%) followed by a character that specifies the type of data.

In C, common format specifiers are:

  • %d: Used for printing integers.
  • %f: Used to format and print single-precision floating-point numbers (float).
  • %lf: Used to format and print double-precision floating-point numbers (double).
  • %c: Used for printing characters.
  • %s: Used for printing strings (char array)
  • %p: Used for a pointer and it prints memory address

Use format specifiers in C

%d for Interger Data Type

'%d' is used in the code printf("Integer: %d\n", num); to format the integer data type 'num'.

%f for Float Data Type

'%f' is used in the code printf("Float: %f\n", floatNum); to format the float data type 'floatNum' variable.

%lf for Double Data Type

'%lf' is used in the code printf("Double %lf", doubleValue); to format the double data type 'doubleValue' variable. '%f' also works for double data type.

%c for Character Data Type

'%c' is used in the code printf("Character: %c", character); to format the char data type 'character' variable.

%s for String (char array)

'%s' is used in the code printf("String: %s", strg); to format the string (char array) data 'strg' variable.

%p for pointer

'%p' is used in the code printf("Pointer: %p", ptr); to format the pointer 'ptr' variable. It prints the memory address of 'num' variable stored in the pointer 'ptr'.

Examples of Format Specifiers in C


Output of the above example

Integer: 999
Float: 12.50
Double 123.456000
Character: A
String: Hello world

Live Code Playground

In the following C code editor, you can practice by formatting more data types. Click the 'Execute Code' button to execute the code; the executed output will be displayed in the following C Code Output frame. Practice until you become comfortable and proficient with your code.

C logo C Online Editor
C Code Output