Format Specifiers in C

In C programming, format specifiers are used to specify the type of data to be printed or read. Format specifiers define the format in which data is printed or read. These specifiers help in displaying the data in a specific format, and they play a vital role in the input/output operations of the program. In this article, we will discuss the format specifiers in C and their usage.


(toc)


Format Specifiers in C

Format specifiers are used in C to control how data is printed to the console or written to a file. They are used with functions like printf and scanf.


Common Format Specifiers:

Format SpecifierData TypeMeaning
%dintDecimal integer
%ffloat or doubleFloating-point number
%ccharCharacter
%schar *String
%pvoid *Pointer address
%xintHexadecimal integer
%ointOctal integer
%uunsigned intUnsigned decimal integer

Example:


int age = 25;
float pi = 3.14159;
char name[] = "Alice";

printf("My name is %s and I am %d years old.\n", name, age);
printf("The value of pi is: %f\n", pi);

Output:

My name is Alice and I am 25 years old.
The value of pi is: 3.141590

Field Width and Precision

You can control the field width and precision of the output using modifiers within the format specifier:

  • %md: Specifies a minimum field width of m characters for the integer.
  • %.nf: Specifies a precision of n decimal places for the floating-point number.
  • %-md: Left-justifies the output within the specified field width.
  • %0md: Fills the field with zeros if the value is shorter than the specified width.

Example:


int number = 123;
float value = 3.14159;

printf("%-10d %08.2f\n", number, value);

Output:

123        0003.14

Additional Format Specifiers

There are other format specifiers available for different data types, such as:

  • %ld: Long integer
  • %lld: Long long integer
  • %lf: Long double
  • %x: Hexadecimal integer (uppercase)
  • %X: Hexadecimal integer (lowercase)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Ok, Go it!