C Tutorial (4) : printf

You have to be able to view the results of a program. C’s primary means of output is the printf() function. printf() produces output on your screen.

The printf() function takes many forms, but when you get used to its format, printf() is easy to use. Here is the general format of printf():

printf(controlString [, data]);

The format is the general look of the statement. Data in the printf function just shown, that part of the statement is optional. printf() requires a controlString, but the data following the controlString is optional.

Warning : printf() doesn’t actually send output to your screen, but it does send it to your computer’s standard output device. Most operating systems, including Windows, route the standard output to your screen unless you know enough to route the output elsewhere. Most of the time, you can ignore this standard output device stuff because you’ll almost always want output to go to the screen. Other C functions you will learn about later route output to your printer and disk drives.

Here is an example of a printf():

printf("My favorite number is %d", 7); // Prints My favorite number is 7

Because every string in C must be enclosed in quotation marks the controlString must be in quotation marks. Anything following the controlString is optional and is determined by the values you want printed.

Note : Every C command and function needs a semicolon (;) after it to let C know that the line is finished. Braces and the first lines of functions don’t need semicolons because nothing is executing on those lines. All statements with printf() should end in a semicolon. You won’t see semicolons after main(), however, because you don’t explicitly tell C to execute main(). You do, however, tell C to execute printf() and many other functions.

Printing Strings

String messages are the easiest type of data to print with printf().

printf(“You are on your way to C mastery”);

The following two printf() statements might not produce the output you expect:

printf(“Write code”);

printf(“Learn C”);

Here is what the two printf() statements produce:

Write codeLearn C

Tip : C does not automatically move the cursor down to the next line when a printf() executes. You must insert an escape sequence in the controlString if you want C to go to the next line after a printf().

Escape Sequences

C contains a lot of escape sequences. Table contains a list of some of the more popular escape sequences.

c_escape_seq

Note : The term escape sequence sounds harder than it really is. An escape sequence is stored as a single character in C and produces the effect described in Table 4.1. When C sends ‘\a’ to the screen, for example, the computer’s bell sounds instead of the characters \ and a actually being printed.

You will see a lot of escape sequences in printf() functions. Any time you want to “move down” to the next line when printing lines of text, you must type \n so that C produces a newline, which moves the blinking cursor down to the next line on the screen. The following printf() statements print their messages on separate lines because of the \n at the end of the first one:

printf("Write code\n");
printf("Learn C");

Tip : The \n could have been placed at the beginning of the second line, and the same output would have occurred. Because escape sequences are characters to C, you must enclose them in quotation marks so that C knows that the escape sequences are part of the string being printed. The following also produces two lines of output:

printf("Write code\nLearn C");

Double quotation marks begin and end a string, single quotation marks begin and end a character, and a backslash signals the start of an escape sequence. There are other escape sequences, but for now, these are the ones you are most likely to use.

printf("\nThe average is %.1f%%.\n", avg);

Tip : To print the percent sign at the end of the final average, two % characters have to be used in the printf() control string. C interprets a percent sign as a control code unless you put two of them together, as done in this program. Then it still interprets the first percent sign as a control code for the second. In other words, the percent sign is a control code for itself.

The following program listing demonstrates the use of all the escape sequences. As always, your best bet is to try this program and then tweak it to something you’d like to try:

#include <stdio.h>

main()
{
/* These three lines show you how to use the most popular Escape Sequences */
printf("Column A\tColumn B\tColumn C");
printf("\nMy Computer\'s Beep Sounds Like This: \a!\n"); 
printf("\"Letz\bs fix that typo and then show the backslash "); 
printf("character \\\" she said\n");

return 0;
}

After you enter, compile, and run this code, you get the following results:

c_escape_seq_op

Note : You should understand a few things about the previous listing. First, you must always place #include at the beginning of all programs that use the printf() function—it is defined in stdio.h, so if you fail to remember that line of code, you will get a compiler error because your program will not understand how to execute printf(). Also, different C/C++ compilers might produce a different number of tabbed spaces for the \t escape sequence. Finally, it is important to note that using the \b escape sequence overwrites anything that was there. That’s why the ‘z’ does not appear in the output, but the ‘s’ does.

Conversion Characters

When you print numbers and characters, you must tell C exactly how to print them. You indicate the format of numbers with conversion characters. Table lists a few of C’s most-used conversion characters.

c_conv_char

When you want to print a value inside a string, insert the appropriate conversion characters in the controlString. Then to the right of the controlString, list the value you want to be printed. Below is an example of how a printf() can print three numbers—an integer, a floating-point value, and another integer.

c_printf_op1

printf() conversion characters determine how and where numbers print.

printf("%s %d %f %c\n", "Sam", 14, -8.76, 'X');

This printf() produces this output:
Sam 14 -8.760000 X

Warning : C is strangely specific when it comes to floating-point numbers. Even though the -8.76 has only two decimal places, C insists on printing six decimal places.

You can control how C prints floating-point values by placing a period (.) and a number between the % and the f of the floating-point conversion character. The number you place determines the number of decimal places your floating-point number prints to.

printf(“%f               %.3f        %.2f        %.1f”, 4.5678, 4.5678, 4.5678, 4.5678);

C rounds the floating-point numbers to the number of decimal places specified in the %.f conversion character and produces this output:

4.567800          4.568         4.57        4.6

The printf() controlString controls exactly how your output will appear. The only reason two spaces appear between the numbers is that the controlString has two spaces between each %f.

Example

#include <stdio.h>

main()
{

/* Here is some more code to help you with printf(), Escape 
  Sequences, and Conversion Characters */ 
printf("Quantity\tCost\tTotal\n"); 
printf("%d\t\t$%.2f\t$%.2f\n", 3, 9.99, 29.97); 
printf("Too many spaces \b\b\b\b can be fixed with the "); 
printf("\\%c Escape character\n", 'b'); 
printf("\n\a\n\a\n\a\n\aSkip a few lines, and beep "); 
printf("a few beeps.\n\n\n");
printf("%s %c.", "You are kicking  butt learning", 'C'); 
printf("You just finished tutorial %d.\nYou have finished ", 4); 
printf("%.1f%c of the series.\n", 12.500, '%'); 
printf("\n\nOne third equals %.2f or ", 0.333333); 
printf("%.3f or %.4f or ", 0.333333, 0.333333); 
printf("%.5f or %.6f\n\n\n", 0.333333, 0.3333333);

return 0;

}

You can place multiple \n characters to jump down as many lines as you want.

Comments < Prev                                                                                          Next > Variables

Advertisements

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s