Printf(): C Library Function

Printf(): C Library Function

Introduction

The printf() is one of the three basic output functions in C. The two others are putchar() and puts() functions. They all send text to the standard output (screen). But while putchar() can write just one character, the puts() function writes a plain string of text without format whereas the printf() function writes formatted string of text which can include formatted variables, special characters such as a new line \n , backspace \b tab \t etc.

The Standard Prototype

Here is the declaration of the printf() function

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

Description

printf() takes at least one argument which is the text to be printed on the standard output. This text can include embed format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype is %[flags][width][.precision][length]specifier Therefore, for the printf() to take more than one argument, the format of the output is defined in the text using a percent (%) character followed by the format specifier.

Common Format Specifiers

printf fs.PNG

Usage

print-variables.png

To use the printf() function in C program first, include the stdio.h header file.

#include <stdio.h>

Next, call theprintf() function and pass the string of text to be printed as the first argument and if there are format variables in the text, then include the values as arguments separated by comma according to how they were stated in the string of text. See samples below

Print a string of text:

printf("I am excellent.\n");

Print a string variable char *name = "Nikki":

printf("My name is %s.\n", name);

Print a integer variable int age = 24:

printf("I am %d years old.\n", age);

Print both string and integer variables:

printf("My name is %s,  I am %d years old.\n", name, age );

Output:

I am excellent.
My name is Nikki.
I am 24 years old.
My name is Nikki, I am 24 years old.

Conclusion

This blog, clearly explains what the C library printf() function is, shows its prototype, usage and carries out some examples.