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.

 

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 Specifier Data Type Meaning
%d int Decimal integer
%f float or double Floating-point number
%c char Character
%s char * String
%p void * Pointer address
%x int Hexadecimal integer
%o int Octal integer
%u unsigned int Unsigned 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: %fn", 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.2fn", 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)

The format specifier in C is used to tell the compiler about the type of data to be printed or scanned in input and output operations. They always start with a % symbol and are used in the formatted string in functions like printf(), scanf, sprintf(), etc.

Related Posts

Leave a Reply