The printf() function is used to print formatted data to stdout(screen). The print function has the general form
int printf("string",[variables...]);
The first argument to printf function is mandatory. It should be a string which contains the text to be printed. It may also contain format specifiers (or conversion specifiers) which are placeholders for arguments that follow. The format specifiers will be in the form
%[flags][width][.precision]type_character
%
and type_character
are mandatory, others are optional.
[flags]
: The available flags are :
Flag | Purpose |
---|---|
+ | This can be used with numeric types to display + or - sign. By default + sign is omitted for positive numbers. |
- | Used to specify the output to be left aligned. By default numbers are aligned to the right. |
0 | Use 0 instead of space for left padding. This flag is used with the width option. |
[width]
Used to specify the minimum number of characters to print. If the width of the actual value to be printed is smaller, then the output will be padded with leading spaces.
[.precision]
Used to specify the number of digits after the decimal point to print for a floating point type. In case of character string type this will denote the number to characters to be printed.
type_character
The type character can be any one of the following letters:
Type Character | For Data Type |
---|---|
d | int |
f | float |
c | Single Character |
s | Character String |
In addition to text and format specifiers you can also have escape sequences in the string argument. The escape sequences start with a backslash (\) and are used to print whitespaces and characters which normally have a special meaning. Most commonly used escape sequences are:
Escape Sequence | Meaning |
---|---|
\\b | Backspace |
\\n | New Line |
\\r | Carriage Return |
\\t | Horizontal Tab |
\\v | Vertical Tab |
\\" | Double Quote |
\\\' | Single Quote |
\\\\ | Backslash |
The string argument of printf function is followed by zero or more variables. Each variable should have a format specifier included in the string argument. The printf function will replace the format specifier with the content of the variable.
The return value of printf function is the number of characters printed on stdout.
#include <stdio.h> int main () { int i = 521; char ch = \'A\'; float x = 12.645; char s[] = "abcd"; printf("%d %c %f %s \\n",i,ch,x,s); printf("%+06d \\n", i); printf("%.2f %.2s \\n",x,s); return 0; }
The output of this program will be
521 A 12.645000 abcd +00521 12.65 ab
Nothing yet..be the first to share wisdom.