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

Leave a Reply: