• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » C » Variables » Formatted Output – the printf Function
Next →
← Prev

Formatted Output – the printf Function

By Dinesh Thakur

The printf (print formatted) standard library function is used to print the values of expressions on standard output (i. e., display) in a specified format. A typical call to the printf function takes the form of a C statement as

printf ( format _string, expr1, expr2, … ) ;

where exprl, expr2, … are expressions whose values are to be printed and format_string specifies how they should be printed. The ellipsis (… ) indicates that the printf function call may contain variable number of expressions. These expressions are optional and may be omitted.

The format string may contain conversion specifications that begin with the %character followed by ordinary characters. The ordinary characters are simply copied to the output stream, i.e., they are printed on the display screen. However, each conversion specification causes the conversion and printing of the next argument expression (exprl, expr2, … )in the format specified by it. For example, the %d conversion specifier prints the next argument expression as an integer, the %f conversion specifier prints it as a floating number (six digits after the decimal point), whereas the %10.2f conversion specifier prints it as a floating number using a minimum field-width of 10 characters and two digits after the decimal point.

The conversion specifications in the format string of the printf function call should match the argument expressions to be printed with regard to the number as well as type. This is the programmer’s responsibility. C compilers usually do not report any errors for mismatch in conversion specifications and arguments. If the conversion specifications are more in number than the argument expressions, the result will be unpredictable. However, excess argument expressions are simply ignored.

The printf function returns an integer value indicating the number of bytes printed. This value is usually ignored in the printf function call..

Example Using the printf function

Consider the printf statement given below.

                    printf(“C is a very easy programming language\n”);

The format string in this call does not contain any conversion specifications. Thus, the given string (c is … language) is printed followed by a new line (\n) causing the cursor to move to the next line as shown below.

                    C is a very easy programming language

Now consider another printf statement given below.

                    printf(“a = %f b = %f ratio= %8.3f”, a, b, a/b);

Observe that the format string contains three conversion specifications (%f, %f and %8.3f) corresponding to three values to be printed (a, band a/b). All other characters are ordinary characters that are simply copied to the display. Thus, if the values of variables a and b are 2.0 and 3.0, respectively, the printf statement displays the output as shown below.

                   a = 2.000000 b = 3.000000 ratio = 0.667

Observe that the values of a, b and a/b have appeared in place of the corresponding conversion Specifiers. The values of a and b are printed using six digits after the decimal places, which is the default for values of float type. The value of expression a/b is printed in a field of eight characters and three digits after the decimal point, as specified in the format 8. 3f.

Printing Strings

The ordinary (i. e., non-formatting) characters in the format string of a printf function call may include graphic as well as non-graphic characters. The graphic characters (letters, digits and symbols such as+, *, /,=, &, $,etc.) in the format string are printed on the display exactly as they appear in the format string. On the other hand, when a non-graphic character is printed, the corresponding effect is obtained.

The most common non-graphic characters included in the format string of a printf function call “are newline (\n) and horizontal tab (\t). Newline (\n) causes the cursor to move to the beginning of next line. If the cursor is already on the last line, the display contents are scrolled up and the cursor is moved to the next line. The horizontal tab (\t) causes the cursor to move to the next tab position, which occurs at every eight character positions on each line (i.e., at character positions 1, 9, 17, 25, … ).If the cursor is beyond the last tab position on a line, it usually moves to the beginning of the next line. When the alert character (\a) is printed, the computer responds with a short beeping sound.

Example:  Printing strings using the printf function

a) Printing a single string

                                    printf(“Hello, world”);

This statement prints the string “Hello, world” (without quotes). The cursor remains on same line immediately after the last character printed (din this case). The next printf statement in the program, if any, will begin its output at this position.

b) Printing strings using multiple printf statements

          Consider the printf statements given below:

printf(“Monday”);

printf(“Tuesday”);

printf(“Wednesday”);

These statements produce the following output:

Monday Tuesday Wednesday

Note that there are no spaces between these names. This is because the output of a printf statement appears immediately after the output of previous printf statement. If spaces are desired between the strings, they should be included in the format strings as shown below:

printf(“Monday “);

printf (“Tuesday “) ;

printf(“Wednesday”);

These statements produce the following output:

Monday Tuesday Wednesday

Of course, we can obtain the same output using a single printf statement, given below:

printf(“Monday Tuesday Wednesday”);

c) Using escape sequences in format strings

printf(“Hello Friends\n”);

printf(“C is a very easy programming language\a”);

The first printf statement prints the string Hello Friends followed by a newline (\n).The newline causes the cursor to move to the next line where the output of the next printf statement will begin. Note that the alert or audible bell (\a) causes a short beeping sound to be made after the string in second printf statement is printed. The output is given below.

Hello Friends

C is a very easy programming language (beep)

d) Using tabs to separate output

                  printf(“One\tTwo\tThree\tFour\tFive\tSix”);

Each horizontal tab character (\ t.) in this statement causes the cursor to move to the next tab stop which occurs at every eight characters. The output of this statement is as follows:

One Two Three Four Five Six

We can include multiple tab characters to increase the spacing between the items printed. Moreover, we can also include newline characters to print the output on multiple lines, as follows:

printf(“One\t\tTwo\t\tThree\nFour\t\tFive\t\tSix\n”);

The output of this statement is as follows:

One             Two             Three

Four            Five            Six

Using Conversion Specifications

To print the values of variables and expressions using a printf statement, we use conversion specifications in the format_string of the printf function call. In its simplest form, a conversion specification consists of a percent character (%) followed by a conversion character, as in %c, %d, %f, etc. The commonly used conversion characters are given in Table along with the type of argument expected and conversion performed.

           Table:  The commonly used conversion characters for the print. Function

conversion charactersArgument typeArgument converted to
d, iintSigned decimal notation of the form [-]ddd
fdoubleDecimal notation of the form [-]ddd.dddddd. The default

precision (i. e., digits after decimal point) is six.

cintSingle character, after conversion to unsigned char
scharThe characters from given string are printed until a ‘\ o’ is

encountered

The %d (decimal) and %i (integer) conversion specifications expect an argument of type int which is printed in signed decimal notation as [-]ddd, where d represents a decimal digit. The numbers are printed using minimum digits and the sign is printed only for negative numbers. Note that these conversion specifications can also be used to print arguments of type char.

The %f(floating-point) conversion specification expects an argument of type double and prints it in decimal form as [–]ddd.dddddd, where d represents a decimal digit. The sign is printed only for negative numbers. Also, the numbers are printed using minimum digits before the decimal point but six digits after it. Note that the %f conversion specification can also be used to print arguments of type float,

The %c(character) conversion specification expects an argument of type int and prints it as a character. We can also use %c for arguments of type char as they have integral values. The conversion specification %s (string) expects an argument of type pointer to char (i. e., char * ). Thus, we can use either a string constant or a character array as an argument. The characters in the string or character array are printed until a null character ( \ 0) is encountered.

The format string in the printf function call may contain more than one conversion specifications. The first conversion specification causes the conversion and printing of the first argument expression, i.e., expr1 in the format of the printf statement. Each subsequent conversion specification causes the conversion and printing of the next argument expression.

The conversion specifications and the expressions to be printed must match in number as well as type. Thus, for every expression to be printed, there must be an appropriate conversion specification in the format string. We can use ordinary characters (both graphic and non-graphic) in the format string to improve the readability of the output. The ordinary characters included in the format string are printed on the screen along with the values of arguments in the specified order.

Example:  Using conversion specifications in the printf statement

a) Printing values of different types

Consider the printf statements given below:

printf(“%d %d %d\n”, 10, -100, ‘A’);

printf(“%f %f %f %f\n”, 1.23, 1.23454321, -1.23456789, l.23f);

printf(“%c %c\n”, 65, ‘B’);

printf(“%s %s\n”, “Hello,”, “world”);

Observe that a separate format specification is used for each value being printed. Thus, the number of format specifications in each format string equals the number of values being printed in that printf statement. The use of the newline character (\n) at the end of each format string causes the output of each printf statement to be printed on a separate line. Also, the spaces between the format specifications enable us to avoid mixing of output values. The output is given below.

10 -100 65

1.230000 1.234543 -1.234568 1.230000

A B

Hello, world

The first printf statement prints values of type int and char using the %d format specifications. Note that the positive numbers are printed without any sign or leading space and character constant ‘A’ is printed as 65, its ASCII code.

The second printf statement prints the values of type double (first three values) and float (1. 23f). Observe that each value is printed using six digits after the decimal point and that the numbers are rounded to the sixth digit. Thus, values 1.23, 1.23454321 and 1.23456789 are printed as 1.230000, 1.234543 and 1.234568, respectively.

Third printf statement uses the %c format specification to print values of type int and char. Note that character constants are printed without single quotes and integer value 65 is printed as A (character representing ASCII value 65).

The last printf statement prints the strings “Hello,” and “world” using the %s format specification. Observe that the quotes surrounding the strings are not printed in the output.

b) Printing expressions

In the previous example, the values to be printed are literal constants. The printf function can also be used to print values of variables and expressions. Consider the example given below.

char c = ‘A’;

int i = 10;

double d = 1.25;

char strl [) = “Hello”, str2 [ ] = “World”;

printf(“%c %c\n”, c + 1, c + i);

printf (“%d %d %d\n”, i, -2 * i, c + 1);

printf(“%f %f %f\n”, d, d * d, d + i);

printf (%s, %s!\n”, strl, str2);

The argument expressions in the first and second printf statements are of type int, whereas those in the third and fourth statements are of type double and string, respectively. Note that the format specifications have been correctly used in these statements with regard to number and type. The output printed by these printf statements is given below.

D T

10 -20 66

1.250000 1.562500 11.250000

Hello, world!

c) Mixing conversion specifications in the format string (Printing values of different types)

A printf statement may be used to print the values of expressions of different types, i. e., we can mix various conversion specifications in a format string of the printf statement. Consider the printf statement given below:

                     printf(“%d %f %s %c”, 100, 10.5, “January”, ‘*’);

In this statement, the format string contains four conversion specifications (%d, %f, %s and %c) used to print constants 100, 10. 5, “January” and ‘* ‘, respectively. Note that the first conversion specification (%d) is correct for the first argument (100 of type int). Similarly, subsequent conversion specifications (%f, %s and %c) are also correct for the next three arguments (10. 5, “January” and ‘* ‘, respectively). The output of this statement is given below.

100 10.500000 January *

d) Making the output more meaningful (Printing text along with values)

Consider the code given below.

int a = 10, b = 20;

printf(“%d %d %d %d”, a, b, a+ b, a* b);

This printf statement displays the output as shown below:

10 20 30 200

We can make this output more meaningful by including text along with conversion specifications as illustrated below.

int a = 10, b = 20;

printf(“Given numbers are a= %d a11db = %d\n”, a, b);

printf(“Their sum is %d and product is %d\n”, a+ b, a* b);

These statements produce the following output:

Given numbers are a = 10 and b = 20

Their sum is 30 and product is 200

e) Mismatch in format specifications and argument expressions

As we already know, proper care must be taken while writing the printf statements as

mismatch in format specification and argument expressions regarding number and type may cause unpredictable results as illustrated below.

int a = 10, b = 20;

float x = 1.2;

printf(“%d %d\n”, a, b, a+ b);

printf(“%d %d %d\n”, a, b);

printf(“%d %f\n”, x, a);

Observe that the format specifications and the argument expressions in these printf statements do not match properly. The first printf statement has an extra argument expression, the second has an extra format specification, whereas the third one has a type mismatch. Note that the compiler does not report any error or warning. When the code is executed using Turbo C, the following output is obtained.

10 20

10 20 2396

0 0.000000

whereas the output obtained using Dev-C++ is as follows:

10 20

10 20 30

1073741824 0.000000

Observe that extra argument in first printf statement is ignored in both cases. However, the extra format specification in second printf statement and the mismatch in format and argument types in third printf statement causes incorrect output to be displayed in both cases.

You’ll also like:

  1. How to Formatted Output using the printf Function
  2. Formatted Input – the scanf Function
  3. Function of printf and scanf in C
  4. What is the Return Value from Printf() Function
  5. Program to See if Printf() Rounds or Truncates
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

C Programming

C Programming Tutorials

  • C - History
  • C - Anatomy
  • C - Constants
  • C - Identifiers
  • C - Data Types
  • C - Libraries File
  • C - Header Files
  • C - Basic Language
  • C - Data Types Sizes
  • C - Header Files Importance
  • C - Escape Sequences
  • C - Main() Purpose
  • C - Program Procedure
  • C - Control Statements
  • C - Enumeration Constant
  • C - Add numbers
  • C - Return Statement
  • C - Avoid Goto
  • C - Command Line Arguments
  • C - Switch Case
  • C - Switch Case Limitations
  • C - getchar() and putchar()
  • C - Iteration Statements
  • C - Pass by Value and Reference
  • C - Structures and Unions
  • C - Structure
  • C - Dynamic Memory
  • C - Fgets and Fputs Functions
  • C - Gets() and Puts() Functions
  • C - Armstrong Number
  • C - Storage Classes
  • C - Fibonacci Series
  • C - Precision Setting
  • C - const Parameters

C - Variable & It's Type

  • C - Variables
  • C - Variable Lifetime
  • C - Static Variable
  • C - Register Variable
  • C - Global Variables
  • C - Auto Variables
  • C - Local Variables

C - Operator & Expressions

  • C - Operator
  • C - Boolean Operators
  • C - Bitwise Operator
  • C - Arithmetic Operators
  • C - Modulus Operator
  • C - Ternary Operator
  • C - Expressions
  • C - Arithmetic Expressions

C - Array

  • C - Arrays
  • C - Array Types
  • C - Array Characteristics
  • C - Static Arrays
  • C - Global Arrays
  • C - 3D Arrays
  • C - Dynamic Arrays
  • C - Pointer to 3D Arrays
  • C - Array Elements Hold
  • C - Arrays as Function Parameters
  • C - Accessing Matrix Elements
  • C - File Handling
  • C - Matrix Multiplication
  • C - Dynamic Memory Allocation

C - Searching & Sorting

  • C - Data Structures
  • C - Linear Search
  • C - Bubble Sort
  • C - Merge Sort
  • C - Linked List
  • C - Insertion Sort
  • C - Binary Search
  • C - Selection Sort
  • C - Quick Sort

C - Functions

  • C - Functions
  • C - Functions Advantages
  • C - Void Functions
  • C - Function Call
  • C - Default Return Value
  • C - String functions

C - Pointer

  • C - Pointers
  • C - Type Casting Of Pointers
  • C - Pointer Advantages
  • C - Pointers Initialization
  • C - Vectors and Pointers

C - Differences

  • C - C Vs C++
  • C - Formal Args. Vs Actual Args.
  • C - Keywords Vs Identifiers
  • C - Strings Vs Character Arrays
  • C - Address Vs Dereference Operator
  • C - Goto Vs longjmp
  • C - Declaring Vs Defining Variable
  • C - String Vs Array
  • C - Call by Value Vs Reference
  • C - Structure Vs Union
  • C - For Vs While loops
  • C - Compiler Vs Interpreter

C - Programs

  • C Program Standard Deviation
  • C Program Calculate Tax
  • C Program Sum Series
  • C Program Merge Arrays
  • C Program Euclid’s Algorithm
  • C Program Print Weekdays
  • C Program Sum of Digits
  • C Program Print a list
  • C Program Print Pythagorean
  • C Program Quiz program
  • C Program Display Table
  • C Program Print Comma-Separated
  • C Program Prints Prime Numbers
  • C Program for Print Integer
  • C Program Count Number
  • C Program Print Color Name
  • C Program Print Odd Numbers
  • C Program Calculate area
  • C Program for a Menu
  • C Program Add Two Vectors
  • C Program Array Addresses
  • C Program Division by Zero Error
  • C Program Compare two Dates
  • C Program Tower of Hanoi
  • C Program return 3 Numbers
  • C Program for Prime Numbers
  • C Program for Factorial
  • C Program for Palindrome

Other Links

  • C Programming - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW