The printf (print formatted) standard library function is used to print the values of expressions on standard output (i. e., display) in a specified format. A typical call to the printf function takes the form of a C statement as
printf ( format _string, expr1, expr2, … ) ;
where exprl, expr2, … are expressions whose values are to be printed and format_string specifies how they should be printed. The ellipsis (… ) indicates that the printf function call may contain variable number of expressions. These expressions are optional and may be omitted.
The format string may contain conversion specifications that begin with the %character followed by ordinary characters. The ordinary characters are simply copied to the output stream, i.e., they are printed on the display screen. However, each conversion specification causes the conversion and printing of the next argument expression (exprl, expr2, … )in the format specified by it. For example, the %d conversion specifier prints the next argument expression as an integer, the %f conversion specifier prints it as a floating number (six digits after the decimal point), whereas the %10.2f conversion specifier prints it as a floating number using a minimum field-width of 10 characters and two digits after the decimal point.
The conversion specifications in the format string of the printf function call should match the argument expressions to be printed with regard to the number as well as type. This is the programmer’s responsibility. C compilers usually do not report any errors for mismatch in conversion specifications and arguments. If the conversion specifications are more in number than the argument expressions, the result will be unpredictable. However, excess argument expressions are simply ignored.
The printf function returns an integer value indicating the number of bytes printed. This value is usually ignored in the printf function call..
Example Using the printf function
Consider the printf statement given below.
printf(“C is a very easy programming language\n”);
The format string in this call does not contain any conversion specifications. Thus, the given string (c is … language) is printed followed by a new line (\n) causing the cursor to move to the next line as shown below.
C is a very easy programming language
Now consider another printf statement given below.
printf(“a = %f b = %f ratio= %8.3f”, a, b, a/b);
Observe that the format string contains three conversion specifications (%f, %f and %8.3f) corresponding to three values to be printed (a, band a/b). All other characters are ordinary characters that are simply copied to the display. Thus, if the values of variables a and b are 2.0 and 3.0, respectively, the printf statement displays the output as shown below.
a = 2.000000 b = 3.000000 ratio = 0.667
Observe that the values of a, b and a/b have appeared in place of the corresponding conversion Specifiers. The values of a and b are printed using six digits after the decimal places, which is the default for values of float type. The value of expression a/b is printed in a field of eight characters and three digits after the decimal point, as specified in the format 8. 3f.
Printing Strings
The ordinary (i. e., non-formatting) characters in the format string of a printf function call may include graphic as well as non-graphic characters. The graphic characters (letters, digits and symbols such as+, *, /,=, &, $,etc.) in the format string are printed on the display exactly as they appear in the format string. On the other hand, when a non-graphic character is printed, the corresponding effect is obtained.
The most common non-graphic characters included in the format string of a printf function call “are newline (\n) and horizontal tab (\t). Newline (\n) causes the cursor to move to the beginning of next line. If the cursor is already on the last line, the display contents are scrolled up and the cursor is moved to the next line. The horizontal tab (\t) causes the cursor to move to the next tab position, which occurs at every eight character positions on each line (i.e., at character positions 1, 9, 17, 25, … ).If the cursor is beyond the last tab position on a line, it usually moves to the beginning of the next line. When the alert character (\a) is printed, the computer responds with a short beeping sound.
Example: Printing strings using the printf function
a) Printing a single string
printf(“Hello, world”);
This statement prints the string “Hello, world” (without quotes). The cursor remains on same line immediately after the last character printed (din this case). The next printf statement in the program, if any, will begin its output at this position.
b) Printing strings using multiple printf statements
Consider the printf statements given below:
printf(“Monday”);
printf(“Tuesday”);
printf(“Wednesday”);
These statements produce the following output:
Monday Tuesday Wednesday
Note that there are no spaces between these names. This is because the output of a printf statement appears immediately after the output of previous printf statement. If spaces are desired between the strings, they should be included in the format strings as shown below:
printf(“Monday “);
printf (“Tuesday “) ;
printf(“Wednesday”);
These statements produce the following output:
Monday Tuesday Wednesday
Of course, we can obtain the same output using a single printf statement, given below:
printf(“Monday Tuesday Wednesday”);
c) Using escape sequences in format strings
printf(“Hello Friends\n”);
printf(“C is a very easy programming language\a”);
The first printf statement prints the string Hello Friends followed by a newline (\n).The newline causes the cursor to move to the next line where the output of the next printf statement will begin. Note that the alert or audible bell (\a) causes a short beeping sound to be made after the string in second printf statement is printed. The output is given below.
Hello Friends
C is a very easy programming language (beep)
d) Using tabs to separate output
printf(“One\tTwo\tThree\tFour\tFive\tSix”);
Each horizontal tab character (\ t.) in this statement causes the cursor to move to the next tab stop which occurs at every eight characters. The output of this statement is as follows:
One Two Three Four Five Six
We can include multiple tab characters to increase the spacing between the items printed. Moreover, we can also include newline characters to print the output on multiple lines, as follows:
printf(“One\t\tTwo\t\tThree\nFour\t\tFive\t\tSix\n”);
The output of this statement is as follows:
One Two Three
Four Five Six
Using Conversion Specifications
To print the values of variables and expressions using a printf statement, we use conversion specifications in the format_string of the printf function call. In its simplest form, a conversion specification consists of a percent character (%) followed by a conversion character, as in %c, %d, %f, etc. The commonly used conversion characters are given in Table along with the type of argument expected and conversion performed.
Table: The commonly used conversion characters for the print. Function
conversion characters | Argument type | Argument converted to |
d, i | int | Signed decimal notation of the form [-]ddd |
f | double | Decimal notation of the form [-]ddd.dddddd. The default precision (i. e., digits after decimal point) is six. |
c | int | Single character, after conversion to unsigned char |
s | char | The characters from given string are printed until a ‘\ o’ is encountered |
The %d (decimal) and %i (integer) conversion specifications expect an argument of type int which is printed in signed decimal notation as [-]ddd, where d represents a decimal digit. The numbers are printed using minimum digits and the sign is printed only for negative numbers. Note that these conversion specifications can also be used to print arguments of type char.
The %f(floating-point) conversion specification expects an argument of type double and prints it in decimal form as [–]ddd.dddddd, where d represents a decimal digit. The sign is printed only for negative numbers. Also, the numbers are printed using minimum digits before the decimal point but six digits after it. Note that the %f conversion specification can also be used to print arguments of type float,
The %c(character) conversion specification expects an argument of type int and prints it as a character. We can also use %c for arguments of type char as they have integral values. The conversion specification %s (string) expects an argument of type pointer to char (i. e., char * ). Thus, we can use either a string constant or a character array as an argument. The characters in the string or character array are printed until a null character ( \ 0) is encountered.
The format string in the printf function call may contain more than one conversion specifications. The first conversion specification causes the conversion and printing of the first argument expression, i.e., expr1 in the format of the printf statement. Each subsequent conversion specification causes the conversion and printing of the next argument expression.
The conversion specifications and the expressions to be printed must match in number as well as type. Thus, for every expression to be printed, there must be an appropriate conversion specification in the format string. We can use ordinary characters (both graphic and non-graphic) in the format string to improve the readability of the output. The ordinary characters included in the format string are printed on the screen along with the values of arguments in the specified order.
Example: Using conversion specifications in the printf statement
a) Printing values of different types
Consider the printf statements given below:
printf(“%d %d %d\n”, 10, -100, ‘A’);
printf(“%f %f %f %f\n”, 1.23, 1.23454321, -1.23456789, l.23f);
printf(“%c %c\n”, 65, ‘B’);
printf(“%s %s\n”, “Hello,”, “world”);
Observe that a separate format specification is used for each value being printed. Thus, the number of format specifications in each format string equals the number of values being printed in that printf statement. The use of the newline character (\n) at the end of each format string causes the output of each printf statement to be printed on a separate line. Also, the spaces between the format specifications enable us to avoid mixing of output values. The output is given below.
10 -100 65
1.230000 1.234543 -1.234568 1.230000
A B
Hello, world
The first printf statement prints values of type int and char using the %d format specifications. Note that the positive numbers are printed without any sign or leading space and character constant ‘A’ is printed as 65, its ASCII code.
The second printf statement prints the values of type double (first three values) and float (1. 23f). Observe that each value is printed using six digits after the decimal point and that the numbers are rounded to the sixth digit. Thus, values 1.23, 1.23454321 and 1.23456789 are printed as 1.230000, 1.234543 and 1.234568, respectively.
Third printf statement uses the %c format specification to print values of type int and char. Note that character constants are printed without single quotes and integer value 65 is printed as A (character representing ASCII value 65).
The last printf statement prints the strings “Hello,” and “world” using the %s format specification. Observe that the quotes surrounding the strings are not printed in the output.
b) Printing expressions
In the previous example, the values to be printed are literal constants. The printf function can also be used to print values of variables and expressions. Consider the example given below.
char c = ‘A’;
int i = 10;
double d = 1.25;
char strl [) = “Hello”, str2 [ ] = “World”;
printf(“%c %c\n”, c + 1, c + i);
printf (“%d %d %d\n”, i, -2 * i, c + 1);
printf(“%f %f %f\n”, d, d * d, d + i);
printf (%s, %s!\n”, strl, str2);
The argument expressions in the first and second printf statements are of type int, whereas those in the third and fourth statements are of type double and string, respectively. Note that the format specifications have been correctly used in these statements with regard to number and type. The output printed by these printf statements is given below.
D T
10 -20 66
1.250000 1.562500 11.250000
Hello, world!
c) Mixing conversion specifications in the format string (Printing values of different types)
A printf statement may be used to print the values of expressions of different types, i. e., we can mix various conversion specifications in a format string of the printf statement. Consider the printf statement given below:
printf(“%d %f %s %c”, 100, 10.5, “January”, ‘*’);
In this statement, the format string contains four conversion specifications (%d, %f, %s and %c) used to print constants 100, 10. 5, “January” and ‘* ‘, respectively. Note that the first conversion specification (%d) is correct for the first argument (100 of type int). Similarly, subsequent conversion specifications (%f, %s and %c) are also correct for the next three arguments (10. 5, “January” and ‘* ‘, respectively). The output of this statement is given below.
100 10.500000 January *
d) Making the output more meaningful (Printing text along with values)
Consider the code given below.
int a = 10, b = 20;
printf(“%d %d %d %d”, a, b, a+ b, a* b);
This printf statement displays the output as shown below:
10 20 30 200
We can make this output more meaningful by including text along with conversion specifications as illustrated below.
int a = 10, b = 20;
printf(“Given numbers are a= %d a11db = %d\n”, a, b);
printf(“Their sum is %d and product is %d\n”, a+ b, a* b);
These statements produce the following output:
Given numbers are a = 10 and b = 20
Their sum is 30 and product is 200
e) Mismatch in format specifications and argument expressions
As we already know, proper care must be taken while writing the printf statements as
mismatch in format specification and argument expressions regarding number and type may cause unpredictable results as illustrated below.
int a = 10, b = 20;
float x = 1.2;
printf(“%d %d\n”, a, b, a+ b);
printf(“%d %d %d\n”, a, b);
printf(“%d %f\n”, x, a);
Observe that the format specifications and the argument expressions in these printf statements do not match properly. The first printf statement has an extra argument expression, the second has an extra format specification, whereas the third one has a type mismatch. Note that the compiler does not report any error or warning. When the code is executed using Turbo C, the following output is obtained.
10 20
10 20 2396
0 0.000000
whereas the output obtained using Dev-C++ is as follows:
10 20
10 20 30
1073741824 0.000000
Observe that extra argument in first printf statement is ignored in both cases. However, the extra format specification in second printf statement and the mismatch in format and argument types in third printf statement causes incorrect output to be displayed in both cases.