Format Specifiers:
Format specifiers in C are used in input and output functions to specify the type and format of data being processed. They define how the data should be interpreted or displayed.
Common Format Specifiers:
1. Integer Specifiers:
%d: Represents a decimal integer.
%u: Represents an unsigned decimal integer.
%o: Represents an octal integer.
%x or %X: Represents a hexadecimal integer.
Example:
int num = 42;
printf(“%d, %u, %o, %xn”, num, num, num, num);
Output:
42, 42, 52, 2a
2. Floating-Point Specifiers:
%f: Represents a floating-point number.
%e or %E: Represents a floating-point number in scientific notation.
%g or %G: Chooses between %f and %e based on the value.
Example:
double pi = 3.14159;
printf(“%f, %e, %gn”, pi, pi, pi);
Output:
3.141590, 3.141590e+00, 3.14159
3. Character Specifiers:
%c: Represents a character.
Example:
char ch = ‘A’;
printf(“%cn”, ch);
Output:
A
4. String Specifier:
%s: Represents a null-terminated string.
Example:
char name[] = “John”;
printf(“%sn”, name);
Output:
John
5. Pointer Specifier:
%p: Represents a pointer address.
Example:
int var = 10;
int *ptr = &var;
printf(“%pn”, (void*)ptr);
Output:
0x7ffc7fe8a0dc (the actual address may vary)
6. Width and Precision:
%*d: Specifies the minimum field width for an integer.
%.2f: Specifies the number of digits after the decimal point for a floating-point number.
Example:
int number = 42;
printf(“%5dn”, number);
Output:
42