Share this page:

C Language: printf function
(Formatted Write)

In the C Programming Language, the printf function writes a formatted string to the stdout stream.

Syntax

The syntax for the C Language printf function is:

int printf(const char *format, ...);

Parameters or Arguments

format describes the output as well as provides a placeholder to insert the formatted string. Here are a few examples:

Format Explanation Example
%d Display an integer 10
%f Displays a floating-point number in fixed decimal format 10.500000
%.1f Displays a floating-point number with 1 digit after the decimal 10.5
%e Display a floating-point number in exponential (scientific notation) 1.050000e+01
%g Display a floating-point number in either fixed decimal or exponential format depending on the size of the number (will not display trailing zeros) 10.5

Returns

The printf function returns the number of characters that was written. If an error occurs, it will return a negative value.

Required Header

In the C Language, the required header for the printf function is:

#include <stdio.h>

Applies To

In the C Language, the printf function can be used in the following versions:

  • ANSI/ISO 9899-1990

Example

Here are some examples that use the printf function:

printf("%s\n","TechOnTheNet.com");

Result: TechOnTheNet.com
printf("%s is over %d years old.\n","TechOnTheNet.com",10);

Result: TechOnTheNet.com is over 10 years old.
printf("%s is over %d years old and pages load in %f seconds.\n","TechOnTheNet.com",10,1.4);

Result: TechOnTheNet.com is over 10 years old and pages load in 1.400000 seconds.
printf("%s is over %d years old and pages load in %.1f seconds.\n","TechOnTheNet.com",10,1.4);

Result: TechOnTheNet.com is over 10 years old and pages load in 1.4 seconds.

Example - Program Code

Let's look at an example to see how you would use the printf function in C program:

/* Example using printf */

#include <stdio.h>

int main()
{
   int age = 10;
   float load = 1.4;

   printf("TechOnTheNet.com is over %d years old and pages load in %.1f seconds.\n", age, load);

   return 0;
}

This C program would print "TechOnTheNet.com is over 10 years old and pages load in 1.4 seconds."

Similar Functions

Other C functions that are similar to the printf function:

See Also

Other C functions that are noteworthy when dealing with the printf function: