C Tutorial – printf, Format Specifiers, Format Conversions and Formatted Output
In this C programming language tutorial we take another look at the printf function. We will look at how to use format specifiers to print formatted output onto the screen. The topics covered are; a little printf background, format specifiers and conversions, formatting of different types and format conversions of strings.
printf Background
The printf function is not part of the C language, because there is no input or output defined in C language itself. The printf function is just a useful function from the standard library of functions that are accessible by C programs. The behavior of printf is defined in the ANSI standard. If the compiler that you’re using conforms to this standard then all the features and properties should be available to you.
Format Specifiers
There are many format specifiers defined in C. Take a look at the following list:
%i or %d | int |
%c | char |
%f | float (see also the note below) |
%s | string |
Note: %f stands for float, but C language has also a thing called “default argument promotions”.
Default argument promotions happen in variadic functions. Variadic functions are functions (e.g. printf) which take a variable number of arguments. When a variadic function is called, after lvalue-to-rvalue, array-to-pointer, and function-to-pointer conversions, each argument that is a part of the variable argument list undergoes additional conversions known as default argument promotions:
- float arguments are converted to double as in floating-point promotion
- bool, char, short, and unscoped enumerations are converted to int or wider integer types as in integer promotion
So for example, float parameters are converted to doubles, and char’s are converted to int’s. If you actually needed to pass, for example, a char instead of an int, the function would have to convert it back.
That’s enough on that side step of variadic function and “default argument promotions”.
Let us take a look at an example of printf formatted output (that why you here, isn’t it?):
#include<stdio.h>
main()
{
int a,b;
float c,d;
a = 15;
b = a / 2;
printf("%d\n",b);
printf("%3d\n",b);
printf("%03d\n",b);
c = 15.3;
d = c / 3;
printf("%3.2f\n",d);
}
Output of the source above:
7
7
007
5.10
As you can see in the first printf statement we print a decimal. In the second printf statement we print the same decimal, but we use a width (%3d) to say that we want three digits (positions) reserved for the output.
The result is that two “space characters” are placed before printing the character. In the third printf statement we say almost the same as the previous one. Print the output with a width of three digits, but fill the space with 0.
In the fourth printf statement we want to print a float. In this printf statement we want to print three position before the decimal point (called width) and two positions behind the decimal point (called precision).
The \n used in the printf statements is called an escape sequence. In this case it represents a newline character. After printing something to the screen you usually want to print something on the next line. If there is no \n then a next printf command will print the string on the same line. Commonly used escape sequences are:
- \n (newline)
- \t (tab)
- \v (vertical tab)
- \f (new page)
- \b (backspace)
- \r (carriage return)
- \n (newline)
Let’s take another look at a printf formatted output in a more application like example:
#include<stdio.h>
main()
{
int Fahrenheit;
for (Fahrenheit = 0; Fahrenheit <= 300; Fahrenheit = Fahrenheit + 20)
printf("%3d %06.3f\n", Fahrenheit, (5.0/9.0)*(Fahrenheit-32));
}
Output of the source above:
0 -17.778
20 -6.667
40 04.444
60 15.556
80 26.667
100 37.778
120 48.889
140 60.000
160 71.111
180 82.222
200 93.333
220 104.444
240 115.556
260 126.667
280 137.778
300 148.889
As you can see we print the Fahrenheit temperature with a width of 3 positions. The Celsius temperature is printed with a width of 6 positions and a precision of 3 positions after the decimal point. Let’s recap:
- %d (print as a decimal integer)
- %6d (print as a decimal integer with a width of at least 6 wide)
- %f (print as a floating point)
- %4f (print as a floating point with a width of at least 4 wide)
- %.4f (print as a floating point with a precision of four characters after the decimal point)
- %3.2f (print as a floating point at least 3 wide and a precision of 2)
Formatting other Types
Until now we only used integers and floats, but there are more types you can use. Take a look at the following example:
#include<stdio.h>
main()
{
printf("The color: %s\n", "blue");
printf("First number: %d\n", 12345);
printf("Second number: %04d\n", 25);
printf("Third number: %i\n", 1234);
printf("Float number: %3.2f\n", 3.14159);
printf("Hexadecimal: %x\n", 255);
printf("Octal: %o\n", 255);
printf("Unsigned value: %u\n", 150);
printf("Just print the percentage sign %%\n", 10);
}
Output of the source example:
The color: blue
First number: 12345
Second number: 0025
Third number: 1234
Float number: 3.14
Hexadecimal: ff
Octal: 377
Unsigned value: 150
Just print the percentage sign %
Note: In the last printf statement only the percentage sign is printed.
The number 10 in this statement doesn’t matter; it’s not used in the output. So if you want to print a percentage number you would use something like this: printf(“%2d%%\n”, 10); (The output will be 10%)
Formatting Strings
By now you have seen most of the format conversion possible, but there is one type that is a little different
and that are string format conversions. Take a look at the following example:
#include<stdio.h>
main()
{
printf(":%s:\n", "Hello, world!");
printf(":%15s:\n", "Hello, world!");
printf(":%.10s:\n", "Hello, world!");
printf(":%-10s:\n", "Hello, world!");
printf(":%-15s:\n", "Hello, world!");
printf(":%.15s:\n", "Hello, world!");
printf(":%15.10s:\n", "Hello, world!");
printf(":%-15.10s:\n", "Hello, world!");
}
The output of the example above:
:Hello, world!:
: Hello, world!:
:Hello, wor:
:Hello, world!:
:Hello, world! :
:Hello, world!:
: Hello, wor:
:Hello, wor :
As you can see, the string format conversion reacts very different from number format conversions.
- The printf(“:%s:\n”, “Hello, world!”); statement prints the string (nothing special happens.)
- The printf(“:%15s:\n”, “Hello, world!”); statement prints the string, but print 15 characters. If the string is smaller the “empty” positions will be filled with “whitespace.”
- The printf(“:%.10s:\n”, “Hello, world!”); statement prints the string, but print only 10 characters of the string.
- The printf(“:%-10s:\n”, “Hello, world!”); statement prints the string, but prints at least 10 characters. If the string is smaller “whitespace” is added at the end. (See next example.)
- The printf(“:%-15s:\n”, “Hello, world!”); statement prints the string, but prints at least 15 characters. The string in this case is shorter than the defined 15 character, thus “whitespace” is added at the end (defined by the minus sign.)
- The printf(“:%.15s:\n”, “Hello, world!”); statement prints the string, but print only 15 characters of the string. In this case the string is shorter than 15, thus the whole string is printed.
- The printf(“:%15.10s:\n”, “Hello, world!”); statement prints the string, but print 15 characters.
If the string is smaller the “empty” positions will be filled with “whitespace.” But it will only print a maximum of 10 characters, thus only part of new string (old string plus the whitespace positions) is printed. - The printf(“:%-15.10s:\n”, “Hello, world!”); statement prints the string, but it does the exact same thing as the previous statement, accept the “whitespace” is added at the end.
A little warning!
The printf function uses its first argument to determine how many arguments will follow and of what types they are. If you don’t use enough arguments or if they are of the wrong type than printf will get confuses, with as a result wrong answers.
That’s all for this C tutorial. Just make some examples of your own, they are easy to make. This is the only way to learn and see how the format conversions reacts.
Armando problem solution
printf(“%8.lf\n”, arr[0]);
printf(“%9.3lf\n”, arr[1]);
printf(“%12.1lf\n”,arr[2]);
Thank you for your problem
Very nicely explained π
Thanx a lot.This really helped me with my exam preparations.
thank u sir ,it is useful .
Thanks a lot. They are very helpful for us.
very useful, concise and complete!
Crisp & Clear explanation..!! Thanxx
[…] In C, printf is a powerful function with many formats. I found a very good tutorial here. […]
[…] este enlace pueden encontrar diversos ejemplos con el printf para conocer como formatear variables y las prueben […]
relli gud tutorial… thnx a lot..
its gud…
This is very helpful… I like it very much, I hope this will be benificial for everyone……….
I need to print out a float containing a GPS coordinate in decimal values, which is -3.6 (ie: -123.123456)
The last digit(6) is critical since I am measuring down to within 3 meters, and require accurate logging and terminal data parsing.
Is there any way to print the value as well as parsing the float into a string while keeping the precision?
float f2= -80.123456;
sprintf(op, “string %3.6f”, f2);
printf(op);
returns: string -80.123459
— OR —
Is there another way I can parse the value from a string to a decimal and keep the precision?
char read[10] = “-80.123456”;
float lon = (1000000 * (float)atoi(read));
printf(“lf %3.6f\n”, lon);
returns: lf -80000000.000000
I am willing to split the char value into 3 integers, (high=”-80″, mid=”123″, low=”456″) but not sure how to parse it in to parts while maintaining precision. (value range “123.123456” to “-101.123456” read as a string)
I need to print something in the format 0.144231E-03 or 0.88913E+03 etc so 0.number with scientific notation.
Any ideas? Normal scientific notation (e.g. 5.1498587E+03 or 1.2039404-03 etc is no good, I can’t use if for what I need to do)
@Steve,
I hope you realize that unless your GPS is accurate to 3 meters, you are not going to actually have 3 meters of accuracy, regardless of how many decimal points it reports.
Regarding your storage issue. Single precision floats have at most 6 to 9 decimal digits of precision. When converting to a string, you are essentially generating a decimal representation of that float. This means that you are guaranteed that a number with 6 decimal digits can be converted back and forth between a float and it’s string representation (which is decimal). However, any more than that really depends on the number (ie some 7, 8, and 9 digit decimals can be converted exactly while others won’t).
So, in your case, you have an 8 digit decimal number that you first convert to float, then back to decimal (in string form). You should expect that at most, the first 6 digits will match.
In you second example, you used atoi which converts an ascii string to an integer. Integers are whole numbers. They don’t have decimal points. So, the output is exactly what you should have gotten. Try atof.
Thanks. Helped me to quickly revise format specifiers π
tis is so cool!!!
great efforts..thanks a lot.
[…] Format Specifiers & Escape Sequence […]
could any one tell me why in the syntax of printf and scanf 3 dots(…) are used…………
thx…bt i cnt understand the meaning of %d
…..
#Ok Men, very good!!!!
What will Happen If We skip & in Scanf Function??
What is %h, %u Specifiers?
i want some examples on using character set in formatted input and output
Plz i need some programs regarding Format specifier…can yew guys help me in that…
This article solved all my doubts, thank you so much. The string part is also very clearly explained.
printf(“%f%f”)
this statement give error,
printf(“%d%c”)
this one give output as a garbage value
why?
How to print large number in the format ###,###,###?
Thankx!
int 5
Printf(“%d”+46,i)
What will be the output and how
@sonu verma:
Does this compile at all?!
What do you want to reach with this?
You add a constant to a format string!
The application may crash or you get garbage. It depends what is stored 46 later after “%d” in the memory…
what is the use of %p in c
sir how to make the marksheet using only the printf statement with width specifiers
%s is use for read string
%c is for character
but what is use of %LF ??..
pls rply…
what is %g stands for?
It is very useful for me
really help full..thnx
how this will be executed?
n=13224;
printf(“%d”,printf(“%d”,printf(“%d”,n)));
fong: %g means:
Use the shortest representation: %e or %f
i.e. scientific (mantissa/exponent) vs. float representation
M.S. SANDHYA:
I assume that’s e.g. “int n=13224;”, otherwise it won’t compile. It’s executed according to normal parenthesis rules. The innermost printf is parsed first producing the string 13224 which is printed out. The result is then also passed to the middle printf which actually prints (right after the previous result 13224) the length (number of digits) of the innermost string i.e. 5. Then the outermost printf prints the length of this string (i.e. length of “5”), namely 1. Therefore the result is 1322451.
Helpful………..thanks……
Stupid question:
Is there a way to format an integer including the sign in the positive case, i.e.
1 => “+1”
printf(“%d%d%d”);
will give output 013440..
why..???
Can anyone plzz tell me the forma
t specifier if the number is 1.345 and its displayed output is 1.35
int a=20,b=30,c=40;
printf(“%d %d %d”);
output is 40 30 20
i want to know the reason behind it
thanx this help me a lot…..i will be on the exam on this tuesday…wish me luck!!!
i want only using format specifier %c print the int datatype hex datatype float datatype..
how to solve this prob?