Two of the first functions a C programmer will learn are “printf()” and “fprintf().” The printf() function governs output to the user’s monitor, while fprintf() governs output to a file instead. Both printf() and fprintf() operate similarly (and their arguments may be interchangeable), but most C programmers will find themselves using printf() most frequently.

In this article, we’ll discuss when you would use the printf() function, how to use it, and what the most common issues encountered might be. The printf() function is easy enough for beginners in C to learn — and it’s very similar to the “print formatted” functions in many other languages.

C Programming For Beginners

Last Updated August 2019

  • 76 lectures
  • All Levels
4.3 (3,759)

Learn C in ten easy steps on Windows, Mac OS X or Linux | By Huw Collingbourne

Explore Course

When would you use the printf C function?

The printf() function sends data to the user’s computer. This journey takes the information from your code to the user’s screen — and while it’s more complex than it might seem, all you really need to know is that it’s the primary method of presenting output to the user.

Person looking at computer screen

Understandably, that’s critical for an application’s usability. The printf() function may be used to print strings of information, data points, error messages, debugging messages, and other content. 

Whenever you use a program, all the text you see is being “printed” to the screen. Some of that text is static (it never changes), whereas other parts of the text are dynamic (it changes based on variables). In combination with the placement of media (such as images and elements), printed text is what comprises the vast majority of the applications that you interact with.

The printf() function will form the basis of how you interact with the user. It will also form the basis of how you return data to yourself — many programmers frequently use the printf() function to return debugging information so they can peer inside of the program’s state.

Luckily, for a function as powerful as printf(), it’s a fairly simple function to learn.

How do you use printf()?

Now that we know when we might use printf(), we need to know how to use printf(). The printf() function is a very simple function. In fact, it can use a single argument: the data that it’s supposed to print.

This is easiest seen with an example. A “Hello, World!” program in C would look like the following:

#include <stdio.h>
Int main() {
		printf(“Hello, World!”);
		Return 0;
}

The output of the above would be: 

Hello, World!

In the above example, the printf() function is being used to return a simple character string. For the most part, this will be how a developer uses printf(): to return a character string. But printf can also be used for more complex actions, with additional arguments.

You will also see that we include stdio.h in the header, which is required to use the function printf. If you want to learn more about the printf() function, you can hunt down information in stdio.h. “Int main()” is the main function of the program and is required for the program to operate — and “return 0,” tells the program that it is done with that function. You will always need the basic element of main() to run a C program.

Now, consider the following example (which would still need the header file, main(), and return 0, but we will leave that out moving forward for the sake of brevity):

printf(“Your team %s hit with %f percent accuracy.”, “Blue Team”,67.89);

The output of the above would be:

Your team Blue Team hit with 67.89 percent accuracy.

In this example, the “%s” tells the compiler to expect a string, while the “%f” tells the compiler to expect a floating point number. There may be any number of “placeholders” within the initial format string, but the number of placeholders will need to at least meet the number of arguments — there can be excess arguments without problem, but there cannot be excess placeholders.

Note that double quotes are always used around strings — they aren’t necessary for the printf function if a string is not being used. An example could be:

printf(%i, 1);

In this case, the output would be:

1

Because it is an int and not a string, it does not require double quotes. And double quotes can be, as it were, a double-edged sword; you cannot print any double quote inside of a series of double quotes unless you escape it with a slash.

As an example:

printf(“I said, “Hello world!””);

The above code will not compile. It will generate a compiler error. Why? Because it’s trying to open and close new quotes. Instead, you would need to type:

printf(“I said, \“Hello world!\””);

The above code essentially tells the compiler to ignore the quote that’s coming next. The code will print:

I said, “Hello world!”

And it will do so without an error.

In addition to being able to print out different arguments, C can also be used to calculate the results of expressions. The code printf(“2+2=%i”,2*2); would output “2+2=4” to the screen. The calculation of 2*2 would be handled by the compiler.


It should also be noted that excess arguments will not be printed by the compiler. They won’t be entirely ignored; if an excess argument includes a calculation, the compiler will complete the calculation. But the compiler will not send an error because it has received excess arguments, so it is up to the programmer to make sure that all their arguments are being passed through to print.

Static vs. dynamic data with printf() 

So far, we’ve only printed static information with printf(). Even when we included arguments, the data never changed; we knew that it would be the Blue Team and an accuracy of 67.89 percent each time. 

Most computer applications are rarely displaying static data, for obvious reasons. One of the most important aspects of computer applications is their ability to manipulate and change information.

So, let’s take a look at how we might use C with variables, instead:

char h[5] = “hello”;
	char w[5] = “world”;
	printf(“%s %s”, h, w);

This will print:

hello world

Note that we had to place the space between the arguments on our own, or it would have printed “helloworld” instead.

As seen, this is still not dynamic. It will always print “hello world.” But by adding variables (h and w), we’ve made it possible to change those variables, too. If we changed w to “everyone” instead of “world,” for instance, the program would then print “hello everyone.”

When debugging, programmers will frequently use printf() to print out variables that are currently in flux. This gives the programmer key insights into what the program is doing; if the variable sent back isn’t what the programmer expects, then there’s unexpected activity within the program itself. The printf() function can be further used to trace where the application goes wrong.

Format specifiers for the printf() function

How do you control how each piece of data is printed in C? As an example, you might want to print a number as 7, 7.0, or 7.00. You might want to print a string “Hello” as “   Hello” or “   Hello   .” Printing is one part of the printf() function, but formatting is another part altogether. 

There are a number of format specifiers that can be used with the printf() function. They include:

These format specifiers are universal across C functions and can be used with the printf function as they would be used elsewhere in the program. Format specifiers may also have arguments of their own. You can limit the number of significant digits on a floating point, for instance, by using the following format: “%.xf.” As an example, “%.2f” would limit the maximum number of significant numbers to two decimal point values. 

For other format specifiers, you may be able to specify the minimum number of digits, negative numbers, field width, the minimum number of characters, and other formatting essentials. For integers, precision specifies the minimum characters. A danger with format specifiers is that it may not be immediately obvious if you have gotten them wrong.

Of course, more advanced programs may have more complex options for formatting. But the simple printf() function works for any console-based program.

Escape sequences following printf() data

There’s an issue that individuals commonly run into with their printf() function. Let’s say that you run the following code:

printf(“Hello world.”);
	printf(“How are you doing?”);

It will print as follows:

Hello world.How are you doing?

By default, printf() doesn’t have an escape. It doesn’t print a new line; it leaves that up to your formatting. If you want to print formatted information that escapes, you would include a “\n” (new line) as so:

printf(“Hello world.\n”);
	printf(“How are you doing?”);

The output will be:

Hello world.
	How are you doing?

\n is a type of escape sequence; a sequence that can be used to generate special characters. The C compiler does this intentionally, because while you can add an escape if it’s not there, it would be harder to take away an escape if it was there by default. 

There are other types of escape sequences as well:

These escape sequences are similar to format specifiers in that they are compiled by the C compiler rather than being passed along as part of the string. The easiest way to think of these is that they are inputs being sent to the computer one by one. So, if you printed “Goodbye\b\b\b,” it would actually print out “Good” rather than “Goodbye.” The “backspace” button would be pressed three times on what you had written!

Tabs are also notable because tabs tend to vary depending on the system. Tabs are a more convenient measurement than spaces, but they are more inconsistent because you won’t know where elements are relative to each other. 

Field width specifiers for the printf() function

How do you make sure your data isn’t just formatted correctly but readable? When data prints out to a console, it’s often first presented as an unorganized list. But you can use data formatting to print data in a particular field width, which can thereby be used to create organized columns. This is especially important if you are processing large volumes of data.

The field width specifiers are essentially used the same way the precision specifiers are. For a string, the precision is the number of characters.

In the following code, we set each string to be the size of 20:

printf(“%20s%20s”, “user”, “email”);

The code that prints out will be:

  user               email

This isn’t that exciting. But, let’s add another line:

printf(“%20s%20s”,”user”,”email”);
	printf(“\n”);
	printf(“%20s%20s”,”john”,”[email protected]”);

Now we end up with:

   user               email
  john        [email protected]

The data has been justified to the right because each statement is the same size. This is an easy way to keep data in a column. Of course, you could likewise have simply added white space in front of each piece of data yourself — but that would be a far more arduous process. Using flags width precision, you can get to exact columns each time.

Printing wide characters with printf() 

There are two important functions for wide characters within C: wprintf() and wscanf(). These operate almost identically to printf but will print wide characters. Wide characters are characters that are larger than the traditional data size permitted by C (8-bit).

In all other respects, wprintf() will operate like printf(), including the format specifiers, escape sequences, and field width specifiers. It is rare that users will need to print wide characters, but if they find they are trying to print something and it’s failing, they may want to consider that this could be the problem.

The companion function, wscanf(), is used to collect wide characters from the user’s own input, just as scanf() is used to collect regular characters from the user’s input. Without wscanf(), the user won’t be able to input the wide characters they may need to provide. Likewise, without wprintf(), the computer will not be able to display the input back to the user.

What are common issues with printf C?

The printf() function doesn’t know how many arguments it has passed. It will match up arguments with the data it has been given, but it may be given too many or too few arguments. In some cases, this can even become a security vulnerability.

Other problems with printf() include:

The latter of which is probably the most important issue with printf(). As programmers learn, they have a tendency to use printf() to describe the state of the software. For instance, they might use printf() at every iteration of a loop to print out the data that is changing within that loop. 

On its own, this is not a problem; printf() is a very useful tool for debugging. But problems can arise if these debugging messages are left within the code. It’s critical that any debugging messages be controlled by a “debugger” internally so that all debugging messages can be toggled on and off at the discretion of the programmer. In other words, “raw” printf() messages, (messages not toggled on and off on a program level), should never be used for the process of debugging. 

For many programmers, printf() will rapidly become their most used command. A great deal of information has to be displayed to a user throughout a program’s runtime, and printf() is by far the easiest way to do so. Most users will be able to use printf() without any major challenges — but digging deeper into the more advanced options can help users better understand the data management features of C.

Top courses in C (programming language)

C Programming the Basics
Frank Anemaet
4.4 (43)
New
C Programming For Beginners - Master the C Language
Tim Buchalka's Learn Programming Academy, Jason Fedin
4.4 (21,214)
Bestseller
Advanced C Programming Course
Tim Buchalka's Learn Programming Academy, Jason Fedin
4.5 (1,610)
Learn C++ Programming by Making Games
Serge Lansiquot
4.5 (426)
Build Undetectable Malware Using C Language: Ethical Hacking
Aleksa Tamburkovski, Joe Parys
4.7 (828)
C Programming Language: The Ultimate Guide for Beginners
Aptuts Online Coaching, Prashant Nayak
4.5 (154)
C Programming from scratch- Master C Programming
Priyanka Yadav Desai
4.6 (32)
Bestseller
C Programming For Beginners
Huw Collingbourne
4.3 (3,759)
Advanced C Programming: Pointers
Huw Collingbourne
4.7 (2,325)

More C (programming language) Courses

C (programming language) students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.

Request a demo