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 |
| %lf | double |
| %s | string |
Note: %lf stands for long float.
Let’s take a look at an example of printf formatted output:
#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.
this tutorial is very good!!!!!
Yes….
This tutorial is really very helpful!!!!
I like this…
This tutorial made my job easy
Thanks a lot
beautiful tutorial. thanx.
i get confuse in formatting,this description is enough to show how these are working and helpful in formatting even digit or string.
I think you have an error near the bottom of the tutorial when summarizing string formatting…
‘The printf(“:%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.” ‘
This should say:
‘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.” ‘
Thx, I have corrected the typo!
I have a problem when printing large floating point numbers.
I tried the following solution but it doesn’t work.
#include <stdio.h>
main()
{
int i;
double arr[3] =
{12345678.000, 98765345.333, 456793332.300};
for (i = 0; i < 3; i++)
printf ("%g\n", arr[i]);
}
The output is this:
1.23457e+07
9.87653e+07
4.56793e+08
What I need is this:
12345678
98765345.333
456793332.3
Could anyone help me?
@Armando – just change printf (“%g\n”, arr[i]); to printf (“%f\n”, arr[i]);
@Social Media Graphics thanks for your suggestion.
But what I really need is to print the decimal significant if any, otherwise only the integer part.
Very good and detail explanation. Thx alot.
if i have 1294300000000000.000001,
how do i get 0.000001?
i only want the decimal places….
does anybody know?
your tutorial was very helpful to me……..thank a lot……
Joe: to get the decimal part of a float (or double), try this:
float x=1294300000000000.000001;
float decimal = x – (int)x;
the conversion to an int should truncate the decimal off. However, I should warn that decimal might not be exactly .000001 here because that is actually impossible to represent in binary, because it is in fact in binary a repeating “decimal.” You might also get nicer results using larger data types like doubles and longs.
Thanks For Your Very Helpful Tutorial
thank u ….. superb explanation …. it made me clear in formatting strings…..
answer to armando problem on 12 th feb.
just write
printf(“%.8g\n”,arr[i]);
printf(“%.11g\n”,arr[i]);
printf(“%.10g\n”,arr[i]);
note:u have to write like above,but not in loop bcoz this only serve ur requirement.
waiting for ur another problem.
Good stuff for beginners but you should include some examples of %U format specifier with its explanation. Best of Luck
Very good exmples – I am using this in awk
but How do I print 10,123,456 – comma after each thousand. I saw some where else to use “%’d” but that is causing problem. ANy ideas.
Thanks
i am trying to print two strings that are stored in char arrays. I can’t get them onto the same line.
char firstName[50];
char lastName[50];
printf(“Your name is %s”, firstName, lastName);
it prints out:
Your name is ‘firstName’
‘lastName’
how do i get them onto the same line??? In other words, how to I add to the printf function?
@ Matt Bates – The source code you have given should only print ‘firstName’, because you only use one %s in your printf statement. So I don’t know why it’s also printing ‘lastName’ (maybe an extra printf statement that you’ve not put in your example.) But below you’ll find an example that should do what you want:
#include
void main() {
char *firstName;
char *lastName;
firstName = “John”;
lastName = “Doe”;
printf(“Your name is %s %s”, firstName, lastName);
}
Good luck!
How do you print a number in binary format (similar to %o, %d, %x)?
Thanks!
There is no format (similar to %d) to print a integer in binary format, you have to build it yourself, a int2bin if you will.
Something like this will do:
#include<stdio.h>void bin(int i) {
int a=0;
if(i!=0) {
a=i;
bin(i>>1);
printf(" %d ", a&0x01);
}
}
int main() {
int b=13;
bin(b);
return 0;
}
thanks a lot. i have exam today and this helped me a lot. i had no idea about the printf thing
thanks! Helped me pick it up quickly, better than wikipedia
i like information abt printf
You could also use the “itoa” function (from stdlib.h) with a radix of 2 to do the conversion from an integer to a string that represents the binary value of the integer.
@tallen387
My previous comment is for you
Hello,
I need to print 10 numbers with one number per line and then beside each number display the running total of digits in the numbers.
example:
num digits
3 1
78 3
890 6
1000 10
etc..
I know a couple of methods to do this and they work. But I am asked to use the “%n conversion specifier” or the ‘n’ format specifier(not even sure what it is actually known as). I guess this would be within the printf as I print out the numbers. But I have tried to search around to find out how this conversion specifier works but have figured out barely anything. I am lost as to how this method would work in counting and displaying the running total of digits.
If somebody could point me in the right direction I would greatly appreciate it.
Thank you.
vry useful tutorial
Great Tutorial. very informative…..
Really helpful and informative tutorial. I hope every one likes it.
Best c printf tutorial so far..
great job!
awesome man!!!!!!!! nice tut..
Hi all,
I need to print a floating number (for example 1009.23) without the decimal point (in this case 100923), just to put it in a formatted positional output.
Can I use printf in some way to do this?
Thank you!
awesome…this tut helped me lot.
i need to know how to print bits or bytes character value in c
hi dude s this is praga ….i need to know exactly whats the reason that we enclose the words to be displayed….meant the words in printf to be enclosed in double quotes
this tut is gr8
[...] Have you checked out Keil's User Guide: Cx51 User's Guide – printf() A couple of good tutorials: C Tutorial – printf, Format Specifiers, Format Conversions and Formatted Output Secrets of “printf” The Keil compiler sends printf() output to STDOUT, which I [...]
nice explanation given!!!!!
Very clear and detailed explanation is given
very nice tut…
Simple stuff but helps a lot in real life programming.
Thanks for the information.
Excellent explanations….
It helps a lot..
Thank u…
nice tutorial…more about the format specifiers
One of best information uploaded!
This a realy useful site for student
THANKS FOR THE INFORMATION.THIS WAS REALLY USEFUL TO ME
Could you help me please
I need show a message as a BOLD .
But I don’t know how to do this…
Please help..
thanx c tutorial………..u help me alot…………
Your examples give me a clear idea about this topic..
Thanks a lot…
best c-tutorials website…. I ever visit…
Facebook.com/kaviraj.kalsi
print the value of variable without using format specifier in c
thanks
Thsnks. Helped me figure out the specifier for double!
awesome man….it rocks…^
Just what I needed, with great examples! Thank you!
This website helps me a lot. thanx
this is wat i want thanks…
good one.
anybody suggest me plz ??
is there any difference between ++a and a++
and when we assign a=2 then what what will return by above ++a and a++ !!!!!
anybody suggest output ????
int main()
{
int i=2;
for(;i<4;)
printf("%d %d ", i++,++i)
return 0;
}
very nice…….
thanks.
#include
int main()
{
float f=43.20;
printf(“%e\n”,f);
printf(“%f\n”,f);
printf(“%g\n”,f);
return 0;
}
What are the significance of %e,%g in the above program?
@Prash
The o/p will vary compiler to compiler
{
char c[]=”GATE2011″;
char *p=c;
printf(“%s”,p+p[3]-p[1]);
}
o/p is 2011
please explain how the o/p is coming 2011?
thanx for the tutorial…helped me a lot in understanding string format conversions with all the width and precisions
How to print values of variables without using format specifier pl help me
Very very useful information. Very complete and simple. The best “printf” tutorial so far. Is there some similar tutorial about “scanf”?
float B=9876.54321;
printf(“\n\t%12.5G”,B);
why the out put is not 9876.54321?
@smith : This is because of the specifier G. The specifier G outputs the shorter of %E or %f. But the precision value is interpreted differently in “G” format than in “f” format. The precision for “f” specifies the number of digits after the decimal point. The precision for “G” specifies the maximum number of significant digits printed.
Try the three specifiers by printing the value, for example:
#include<stdio.h>
int main {
float B=9876.54321;
printf(“%12.5G\n”, B);
printf(“%12.5f\n”, B);
printf(“%12.5E\n”, B);
}
Good Luck!
Bravo!
Well done tutorial this!
i benefitted from this information
its great !! made my work easier .
Hi, . Any way to represent floating point numbers in C ?. .
Like for 24bit
-256.327 *10^0
a)binary representation is
1 .1000000000101000 000100
b)for octal
1 .1000000000101001 0000011
so how could one print this kind of output ?
realy very helpfull..
well written. will mind sending more notes on c programming
nice..
very nice ..thx a lot for this site owner…
this tutorial is really very good
and very useful for the beginners,………………..
thanks a lot,
Very nice but I have a complicated display to put: I got the two first digits of an IP address (in float) and I would like to display it but with always the . (dot) in 4th position and the correct value for the second octet.
Currently it gives me:
25.000 instead of 25.0
138.350 instead of 138.35 and dot are not aligned.
Do you have a magic way to proceed only with format specifier because I can only provide a format, not add new values?
very helpful in understandind concept of format specifier
Its very usefull to all & it is very good…nice tutorial..
Q))
char c=”gate2011″;
char*p=c;
printf(“%s”,p+p[3]-p[1]);
what wil be the output of the following code fragment??
@shalini – First of it should be char c[] = “gate2011″; otherwise you’ll get something like – warning: initialization makes integer from pointer without a cast. But if you run the code the output will be 2011.
char *c=”gate2011″
…..
…
will give output 2011 becoz
Going through each line in turn:
char c[] = “gate2011″;
Let’s assume that array c is located at memory address 200.
char *p = c;
p is now a pointer to c. It therefore points to memory address 200. The actual content of p is “200″, indicating the memory address.
printf(“%s”, p + p[3] – p[1]);
The value of p is 200 when we treat it like a pointer. However, we can also treat it like an array. p[3] gets the value of the 4th item in the string, which is “e”. C stores characters as their ASCII value. The ASCII value of “e” is 101.
Next, we get the value of p[1]. p[1] == “a”, which has an ASCII value of 97. Substituting these into the function:
printf(“%s”, 200 + 101 – 97);
That evaluates to:
printf(“%s”, 204);
At memory address 204, we have the string “2011″. Therefore, the program prints “2011″.
Why don’t you put some // example 1 // at end where it is easier to see along with matching that when you print it out.
Because it takes longer the way it is listed. You have 6 / 7 things, hard to tell which line.
this tutorial is very useful thanks for help………
thank U for this helpfu tutorial.
its really very helpful to me. so, thanks a lot.
Thanks this really help me to flashback
thank u so much it used to my studies thanks a lot
This website rox !!!!!
How to printf the \n itself ?
@Arist: If you want to print the \n itself, then you need to escape the \ by adding another \ (the slash is escape character). So you will get \\n. Take a look at the following source example:
#include<stdio.h>
int main() {
printf(“\\n”);
printf(“\n\” \”");
return 0;
}
The first printf statement will print \n and the second printf statement will print ” ” (so we escaped the ” characters).
really this is very helpful for knowing the concept of c-programming.
apart from all there are many confusing concept which make a great trouble in
programming with c-language.
but slowly by help of this tutorial all get clear.
thnx to all.. .. ..2n41
Thank you for this useful information
using only printf how to print 12.450
like 012.45 using 3 numbers before decimal point it’s can be 002.45 depend how many numbers before it’s should be
“%3.2Lf” but i need also zeros if needed
@Rahul
In ur pgm code, p[3] = ‘E’ and p[1] = ‘A’.
And ‘E’ – ‘A’ = 4 (diff. of their ascii values)
and p + 4 = p[4] (add. of p + 4 int places),
So printf(“%s”,p+p[3]-p[1]);
is equivalent to
printf(“%s”,p[4]);
and the string at p[4] is “2011″.
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)