Format Specifier | Associated Datatype | Description |
---|---|---|
%c | char | Used to format single character |
%d or %i | int | Used to format a signed integer |
%u | int | Used to format an unsigned integer in decimal form |
%o | int | Used to format an unsigned integer in octal form |
%x or %X | int | Used to format an unsigned integer in hex form |
%h | int | Used to format an short integer |
%e or %E | float or double | Used to format a float or double in exponential form |
%f | float or double | Used to format a float or double in decimal format |
%s | char[] | Used to format a string/character sequence |
Example of Print Format Specifiers
Now that we know how to print any data type, let's take a look at a simple example.
- #include <stdio.h>
- int main()
- {
- int i = 30;
- char c = 'z';
- float f = 5.67;
- char s[] = "This is a string";
- printf("i=%d, c=%c, f=%f, s=%s", i,c,f,s);
- return 0;
- }
- Output:
- i=30, c=z, f=5.670000, s=This is a string
In this program, we've got some familiar variable declaration; one
int
, one char
one float
and one string (char[]
). After declaring and assigning values to the variables, we invoked a printf
statement which print contents between two double inverted commas to the standard output or the screen. The contents are written in the screen using print format specifiers, which replace the values of the variables that appears after closing '"'.
Here
%d
is replaced by decimal value of the variable 'i' which is 30, %c
is replaced by the character stored in variable 'c', %f
is replaced by the floating point value with variable 'f' and %s
is replaced by the string represented by array 's'. Note the order of the print format specifiers are same as the order of variables appearing in the printf
statement. The order of declaration does not matter as long as you declare the variables before you print them.
No comments:
Post a Comment