totn C Functions

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 printf function in the C Language 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:

FormatExplanationExample
%dDisplay an integer10
%fDisplays a floating-point number in fixed decimal format10.500000
%.1fDisplays a floating-point number with 1 digit after the decimal10.5
%eDisplay a floating-point number in exponential (scientific notation)1.050000e+01
%gDisplay 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

printf 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 a C program:

/* Example using printf */

#include <stdio.h>

int main(int argc, const char * argv[])
{
    /* Define variables */
    int age = 10;
    float load = 1.4;

    /* Display the results using the appropriate format strings for each variable */
    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: