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
xxxxxxxxxx
int num = 999;
printf("Integer: %d", num);
'%d'
is used in the code printf("Integer: %d\n", num);
to format the integer data type 'num'.
%f for Float Data Type
xxxxxxxxxx
float floatNum = 12.50;
printf("Float: %f\n", floatNum);
'%f'
is used in the code printf("Float: %f\n", floatNum);
to format the float data type 'floatNum' variable.
%lf for Double Data Type
xxxxxxxxxx
double doubleValue = 123.456;
printf("Double %lf", value);
'%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
xxxxxxxxxx
char character = 'A';
printf("Character: %c", character);
'%c'
is used in the code printf("Character: %c", character);
to format the char data type 'character' variable.
%s for String (char array)
xxxxxxxxxx
char strg[] = "Hello world";
printf("String: %s", strg);
'%s'
is used in the code printf("String: %s", strg);
to format the string (char array) data 'strg' variable.
%p for pointer
xxxxxxxxxx
int num = 12;
int *ptr = #
printf("Pointer: %p", ptr);
'%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
xxxxxxxxxx
#include <stdio.h>
int main() {
int num = 999;
printf("Integer: %d\n", num); //'\n' is used to create a new line
float floatNum = 12.50;
printf("Float: %.2f\n", floatNum); // Formats float to 2 decimal places
double doubleValue = 123.456;
printf("Double %lf\n", doubleValue);
char character = 'A';
printf("Character: %c\n", character);
char string[] = "Hello world";
printf("String: %s\n", string);
return 0;
}
Output of the above example
Integer: 999 Float: 12.50 Double 123.456000 Character: A String: Hello world