| |
3. Formatted Output - printf
|
| |
The output function printf translates internal values to characters. |
int printf(char *format, arg1, arg2, ...);
printf() can be used for formatted output.
It takes in a variable number of arguments.
It returns the number of characters printed.
The format can contain literal strings as well as format specifiers (starts with %). |
| |
| Example |
printf("hello world\n”);
printf("%d\n”, 10); // format: %d (integer),
// argument: 10
printf("Prices: %d and %d\n”, 10, 20); |
|
| |
| printf format specification |
The format specification has the following components |
| |
| %[flags][width][.precision][length]<type> |
|
| |
| type: |
| type |
meaning |
example |
output |
| d, i |
integer |
printf ("%d",10); |
10 |
| x, X |
integer(hex) |
printf ("%x",10); |
0xa |
| u |
unsigned integer |
printf ("%u",10 |
10 |
| c |
character |
printf ("%c",’A |
A |
| s |
string |
printf ("%s","hello"); |
hello |
| f |
float |
printf ("%f",2.3); |
2.3 |
| d |
double |
printf ("%d",2.3); |
2.3 |
| e, E |
float(exp) |
1e3,1.2E3,1E−3 |
1e3,1.2E3,1E−3 |
| % |
literal % |
printf ("%d %%",10); |
10 % |
|
| |
| width: |
 |
| |
| flag: |
 |
| |
| precision: |
 |
| |
| modifier: |
 |
| |
| |
|
|
|