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:

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

printf Example

Here are some examples that use the printf function:




printf("%s\n","c programming");






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






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






Result: c programming 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","c programming",10,1.4);

Result: c programming is over 10 years old and pages load in 1.8 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("c programming is over %d years old and pages load in %.1f seconds.\n", age, load);

    return 0;
}



This C program would print "c programming is over 10 years old and pages load in 1.8 seconds."


stdio.h Functions





Instagram