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.

This entry was posted in C Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. Tweet This! Tweet This! or use to share this post with others.

There are currently 143 responses to “C Tutorial – printf, Format Specifiers, Format Conversions and Formatted Output”

Why not let us know what you think by adding your own comment!

  1. Joe on November 11th, 2009:

    this tutorial is very good!!!!!

  2. Rohit Rajpoot on November 28th, 2009:

    Yes….
    This tutorial is really very helpful!!!!
    I like this…

  3. Deepak on December 9th, 2009:

    This tutorial made my job easy
    Thanks a lot

  4. kaustav on December 13th, 2009:

    beautiful tutorial. thanx.

  5. Aaditya kumar on January 23rd, 2010:

    i get confuse in formatting,this description is enough to show how these are working and helpful in formatting even digit or string.

  6. Matt on February 3rd, 2010:

    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.” ‘

  7. admin on February 3rd, 2010:

    Thx, I have corrected the typo!

  8. Armando on February 12th, 2010:

    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?

  9. Social Media Graphics on February 12th, 2010:

    @Armando – just change printf (“%g\n”, arr[i]); to printf (“%f\n”, arr[i]);

  10. Armando on February 17th, 2010:

    @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.

  11. cheeloon on March 4th, 2010:

    Very good and detail explanation. Thx alot.

  12. Joe on March 12th, 2010:

    if i have 1294300000000000.000001,
    how do i get 0.000001?
    i only want the decimal places….
    does anybody know?

  13. prashanth on April 7th, 2010:

    your tutorial was very helpful to me……..thank a lot……

  14. David on April 8th, 2010:

    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.

  15. Shashika on July 7th, 2010:

    Thanks For Your Very Helpful Tutorial

  16. selva on July 8th, 2010:

    thank u ….. superb explanation …. it made me clear in formatting strings…..

  17. pramit on July 17th, 2010:

    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.

  18. Tushar Srivastava on July 31st, 2010:

    Good stuff for beginners but you should include some examples of %U format specifier with its explanation. Best of Luck

  19. Holo on August 19th, 2010:

    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

  20. Matt Bates on August 24th, 2010:

    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?

  21. admin on August 25th, 2010:

    @ 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!

  22. tallen387 on September 23rd, 2010:

    How do you print a number in binary format (similar to %o, %d, %x)?

    Thanks!

  23. admin on September 24th, 2010:

    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;
    }

  24. sankar v on November 11th, 2010:

    thanks a lot. i have exam today and this helped me a lot. i had no idea about the printf thing

  25. Aggie on December 5th, 2010:

    thanks! Helped me pick it up quickly, better than wikipedia

  26. tanushri on December 14th, 2010:

    i like information abt printf

  27. Deon Joubert on January 19th, 2011:

    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.

  28. Deon Joubert on January 19th, 2011:

    @tallen387
    My previous comment is for you

  29. aaron on January 24th, 2011:

    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.

  30. nancy on March 1st, 2011:

    vry useful tutorial

  31. sha on March 25th, 2011:

    Great Tutorial. very informative…..

  32. Faisal on April 13th, 2011:

    Really helpful and informative tutorial. I hope every one likes it.

  33. Orel on May 6th, 2011:

    Best c printf tutorial so far.. :) great job!

  34. aayush on May 9th, 2011:

    awesome man!!!!!!!! nice tut..

  35. Pisio on May 11th, 2011:

    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!

  36. ranjitha g on May 20th, 2011:

    awesome…this tut helped me lot.

  37. Rahul Singh Chouhan on May 27th, 2011:

    i need to know how to print bits or bytes character value in c

  38. praga on June 7th, 2011:

    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

  39. praga on June 7th, 2011:

    this tut is gr8

  40. Printf() function for debugging process on June 13th, 2011:

    [...] 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 [...]

  41. Anchal on June 16th, 2011:

    nice explanation given!!!!!

  42. sahtihi on June 29th, 2011:

    Very clear and detailed explanation is given

  43. Ganesh Auti,Pune on July 4th, 2011:

    very nice tut…

  44. Aravind on July 5th, 2011:

    Simple stuff but helps a lot in real life programming.
    Thanks for the information.

  45. Brindha on July 15th, 2011:

    Excellent explanations….
    It helps a lot..
    Thank u…

  46. shirin k on July 17th, 2011:

    nice tutorial…more about the format specifiers

  47. Rajesh Joshi on July 18th, 2011:

    One of best information uploaded!

  48. smit on July 30th, 2011:

    This a realy useful site for student

  49. navneeth on August 4th, 2011:

    THANKS FOR THE INFORMATION.THIS WAS REALLY USEFUL TO ME

  50. jesen on August 26th, 2011:

    Could you help me please
    I need show a message as a BOLD .
    But I don’t know how to do this…
    Please help..

  51. thita nayak on September 6th, 2011:

    thanx c tutorial………..u help me alot…………

  52. Arivoli on September 15th, 2011:

    Your examples give me a clear idea about this topic..
    Thanks a lot…

  53. kaviraj on September 19th, 2011:

    best c-tutorials website…. I ever visit…
    Facebook.com/kaviraj.kalsi

  54. avinash on September 26th, 2011:

    print the value of variable without using format specifier in c

  55. dheeraj on October 7th, 2011:

    thanks

  56. Abd on October 9th, 2011:

    Thsnks. Helped me figure out the specifier for double!

  57. amrutanshu on October 18th, 2011:

    awesome man….it rocks…^

  58. Csaba on November 8th, 2011:

    Just what I needed, with great examples! Thank you!

  59. Usman Akram Punjab University Lahore on November 19th, 2011:

    This website helps me a lot. thanx

  60. sunny on November 19th, 2011:

    this is wat i want thanks…

  61. Neeba on November 24th, 2011:

    good one.

  62. Prash on December 31st, 2011:

    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++ !!!!!

  63. Prash on December 31st, 2011:

    anybody suggest output ????

    int main()

    {

    int i=2;

    for(;i<4;)
    printf("%d %d ", i++,++i)

    return 0;
    }

  64. Naveed on January 3rd, 2012:

    very nice…….
    thanks.

  65. Anurag Dake on January 12th, 2012:

    #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?

  66. Anurag Dake on January 12th, 2012:

    @Prash
    The o/p will vary compiler to compiler

  67. Rahul on January 19th, 2012:

    {
    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?

  68. vidya on January 29th, 2012:

    thanx for the tutorial…helped me a lot in understanding string format conversions with all the width and precisions

  69. Ragavi on January 31st, 2012:

    How to print values of variables without using format specifier pl help me

  70. Dario on February 9th, 2012:

    Very very useful information. Very complete and simple. The best “printf” tutorial so far. Is there some similar tutorial about “scanf”?

  71. smith on February 17th, 2012:

    float B=9876.54321;
    printf(“\n\t%12.5G”,B);
    why the out put is not 9876.54321?

  72. Cad on February 17th, 2012:

    @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!

  73. sendsmsdad on February 22nd, 2012:

    Bravo!
    Well done tutorial this!

  74. Saloni Rastogi on March 4th, 2012:

    i benefitted from this information
    its great !! made my work easier .

  75. Arj on March 11th, 2012:

    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 ?

  76. neha on March 20th, 2012:

    realy very helpfull..

  77. simon on April 17th, 2012:

    well written. will mind sending more notes on c programming

  78. kirti on April 20th, 2012:

    nice..

  79. Pulaha on May 4th, 2012:

    very nice ..thx a lot for this site owner…

  80. raj verma on May 19th, 2012:

    this tutorial is really very good
    and very useful for the beginners,………………..

  81. Vipin Patel on June 5th, 2012:

    thanks a lot,

  82. Jackouille on June 10th, 2012:

    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?

  83. ayush on June 26th, 2012:

    very helpful in understandind concept of format specifier

  84. Bhavanishankar on July 5th, 2012:

    Its very usefull to all & it is very good…nice tutorial..

  85. shalini on July 5th, 2012:

    Q))
    char c=”gate2011″;
    char*p=c;
    printf(“%s”,p+p[3]-p[1]);

    what wil be the output of the following code fragment??

  86. admin on July 6th, 2012:

    @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.

  87. sarir on July 13th, 2012:

    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″.

  88. David Blaine Fullerton on July 13th, 2012:

    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.

  89. venu nishad on July 29th, 2012:

    this tutorial is very useful thanks for help………

  90. harisha on August 8th, 2012:

    thank U for this helpfu tutorial.

  91. sukesh on August 16th, 2012:

    its really very helpful to me. so, thanks a lot.

  92. jeff on August 19th, 2012:

    Thanks this really help me to flashback :)

  93. sangeetha on September 2nd, 2012:

    thank u so much it used to my studies thanks a lot

  94. Rishi on September 10th, 2012:

    This website rox !!!!!

  95. arist on September 16th, 2012:

    How to printf the \n itself ?

  96. admin on September 16th, 2012:

    @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).

  97. maddy on September 27th, 2012:

    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

  98. chris on October 3rd, 2012:

    Thank you for this useful information

  99. dim on November 5th, 2012:

    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

  100. Fahad on November 12th, 2012:

    @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″.

  101. loganaayahee on November 21st, 2012:

    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

  102. jasleen on November 25th, 2012:

    Very nicely explained :)

  103. Suraj Rana on November 27th, 2012:

    Thanx a lot.This really helped me with my exam preparations.

  104. janardhan on December 5th, 2012:

    thank u sir ,it is useful .

  105. Haris on December 5th, 2012:

    Thanks a lot. They are very helpful for us.

  106. jason on January 9th, 2013:

    very useful, concise and complete!

  107. Subbu on January 18th, 2013:

    Crisp & Clear explanation..!! Thanxx

  108. Printf Formats | Code Thrower on February 10th, 2013:

    [...] In C, printf is a powerful function with many formats. I found a very good tutorial here. [...]

  109. Tutorial Pinguino – Capitulo 7. USB-CDC Emulación de Puerto Serie | Blog MicroEmbebidos (PIC,MSP430,LPC,RTOS) on March 31st, 2013:

    [...] este enlace pueden encontrar diversos ejemplos con el printf para conocer como formatear variables y las prueben [...]

  110. Ayesha on April 1st, 2013:

    relli gud tutorial… thnx a lot..

  111. neeraj on April 8th, 2013:

    its gud…

  112. Sadam Hussain on April 8th, 2013:

    This is very helpful… I like it very much, I hope this will be benificial for everyone……….

  113. Steve on April 14th, 2013:

    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)

  114. Amy on April 15th, 2013:

    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)

  115. weethomas on May 21st, 2013:

    @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.

  116. Prateek on May 31st, 2013:

    Thanks. Helped me to quickly revise format specifiers :)

  117. karan on June 8th, 2013:

    tis is so cool!!!

  118. Kunal on June 10th, 2013:

    great efforts..thanks a lot.

  119. What is the role of C? What are the various features of C Language. - CareerDrudge on June 15th, 2013:

    [...] Format Specifiers & Escape Sequence [...]

  120. Anushree on July 26th, 2013:

    could any one tell me why in the syntax of printf and scanf 3 dots(…) are used…………

  121. biswajit on August 19th, 2013:

    thx…bt i cnt understand the meaning of %d

    …..

  122. Lilian on September 10th, 2013:

    #Ok Men, very good!!!!

  123. Sumithra on September 11th, 2013:

    What will Happen If We skip & in Scanf Function??
    What is %h, %u Specifiers?

  124. sailakshmi on September 26th, 2013:

    i want some examples on using character set in formatted input and output

  125. mehwish on September 26th, 2013:

    Plz i need some programs regarding Format specifier…can yew guys help me in that…

  126. Amey Chaware on October 2nd, 2013:

    This article solved all my doubts, thank you so much. The string part is also very clearly explained.

  127. ekta on October 2nd, 2013:

    printf(“%f%f”)
    this statement give error,
    printf(“%d%c”)
    this one give output as a garbage value
    why?

  128. Steven Nguyen on October 3rd, 2013:

    How to print large number in the format ###,###,###?

    Thankx!

  129. sonu verma on October 7th, 2013:

    int 5
    Printf(“%d”+46,i)
    What will be the output and how

  130. scotty on October 22nd, 2013:

    @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…

  131. sen on October 31st, 2013:

    what is the use of %p in c

  132. ozee on November 2nd, 2013:

    sir how to make the marksheet using only the printf statement with width specifiers

  133. raj on November 15th, 2013:

    %s is use for read string
    %c is for character
    but what is use of %LF ??..
    pls rply…

  134. fong on November 25th, 2013:

    what is %g stands for?

  135. ragavi on December 11th, 2013:

    It is very useful for me

  136. harish on December 17th, 2013:

    really help full..thnx

  137. M.S. SANDHYA on December 19th, 2013:

    how this will be executed?
    n=13224;
    printf(“%d”,printf(“%d”,printf(“%d”,n)));

  138. Joel Korhonen on December 20th, 2013:

    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.

  139. Giridhar on January 29th, 2014:

    Helpful………..thanks……

  140. Klaus on February 20th, 2014:

    Stupid question:

    Is there a way to format an integer including the sign in the positive case, i.e.

    1 => “+1″

  141. Aayushi Mishra on February 28th, 2014:

    printf(“%d%d%d”);
    will give output 013440..
    why..???

  142. Hamza saghir on March 23rd, 2014:

    Can anyone plzz tell me the forma
    t specifier if the number is 1.345 and its displayed output is 1.35

  143. varun kumar on April 12th, 2014:

    int a=20,b=30,c=40;
    printf(“%d %d %d”);
    output is 40 30 20
    i want to know the reason behind it

Leave a Reply: