• No results found

printf Function

In document Engineering Problem Solving With C (Page 67-70)

Theprintffunction allows us to print values and explanatory text to the screen. For exam-ple, consider the following statement that prints the value of a doublevariable named angle along with the corresponding units:

printf("Angle = %f radians \n",angle);

Thisprintfstatement contains two arguments: a control string and an identifier to specify the value to be printed. A control string is enclosed in double quotation marks, and can con-tain text, conversion specifiers, or both. A conversion specifier describes the format to use in printing the value of a variable. In the previous example, the control string specifies that the charactersAngle =are to be printed. The next group of characters (%f) represents a conver-sion specifier that indicates that a value is to be printed next, which will then be followed by the characters radians. The next combination of characters (\n) represents a new line indi-cator; it causes a skip to a new line on the screen after the information has been printed. The second argument in the printfstatement is a variable angle; it is matched to the conversion specifier in the control string. Thus, the value in angleis printed according to the specifica-tion%f, which will be explained later. If the value of angleis 2.84, then the output generat-ed by the previous statement is

Angle = 2.840000 radians

Now that we have analyzed a simple statement and its corresponding output, we are ready to take a closer look at the conversion specifiers.

To select a conversion specifier for a value to be printed, first select the correct type of specifier as indicated in Table 2.6. For example, to print a shortor an int, use an %i (in-teger) or %d(decimal) specifier (either specifier gives the same results). To print a long, use an %lior%ldspecifier. To print a floator a double, use an %f(floating-point form), Conversion specifier

Table 2.6 Conversion Specifiers for Output Statements

Variable Type Output Type Specifier Integer Values

short, int int %i, %d

int short %hi, %hd

long long %li, %ld

int unsigned int %u

int unsigned short %hu

long unsigned long %lu

Floating-Point Values

float, double double %f, %e, %E, %g, %G long double long double %LF, %Le, %LE, %Lg, %LG

Character Values

char char %c

%e (exponential form, as in 2.3e+02), or %E (exponential form, as in 2.3E+02). The %g (general) specifier prints the value using an %for%especifier, depending on the size of the value; the %Gspecifier is the same as the %g, except that it prints the value using an %for%E specifier.

After selecting the correct specifier, additional information can be added. A minimum field width can be specified, along with an optional precision that controls the number of characters printed. The field width and the precision can be used together or separately. If the precision is omitted, a default of 6 is used for the %fspecifier. The decimal portion of a value is rounded to the specified precision; thus, the value 14.51678 will be printed as 14.52if a

%.2fspecification is used. The specification %5iindicates that a shortor an intis to be printed with a minimum field width of 5. The field width will be increased if necessary to print the corresponding value. If the field width specifies more positions than are needed for the value, the value is right justified, which means that the extra positions are filled with blanks on the left of the value. To left justify a value, a minus sign is inserted before the field width, as in %-8i.If a plus sign is inserted before the field width, as in %+6f, a sign will al-ways be printed with the value.

The following list shows several conversion specifiers and the resulting output fields for a given value; the character bis used to indicate the location of blanks within the field. In these examples, assume that the corresponding integer value is 145:

Specifier Value Printed

The next list shows several conversion specifiers and the resulting output fields for the doublevalue 157.8926:

Note the rounding that occurred with the last two specifiers.

If a control argument contains three conversion specifiers, then three corresponding iden-tifiers or expressions would need to follow the control string, as in this statement:

printf("Results: x = %5.2f, y = %5.2f, z = %5.2f \n", x,y,z+3);

An example output from this statement is

Results: x = 4.52, y = 0.15, z = -1.34

Section 2.4 Standard Input and Output 45

Field width Precision

Right justified Left justify

Note that the last conversion specifier matches to an arithmetic expression instead of a simple variable.

The backslash (\) is called an escape character when it is used in a control string. The compiler combines it with the character that follows it and then attaches a special meaning to the combination of characters. For example, we have already seen that \nrepresents a skip to a new line. In addition, the sequence \\is used to insert a single backslash in a control string, and the sequence \"will insert a double quote in a control string. Thus, the output of the statement

printf("\"The End.\"\n");

is a line containing

"The End."

The other escape sequences recognized by C are as follows:

Sequence Character Represented

\a alert (bell) character

\b backspace

\f formfeed

\n newline

\r carriage return

\t horizontal tab

\v vertical tab

\\ backslash

\? question mark

\' single quote

\" double quote

If a printfstatement is long, you should split it into two lines. In general, long lines should be split at a point that preserves readability. However, to split text that is contained in quotation marks, you should split the text into two separate pieces of text, each in its own set of quotation marks. The following statements show several different ways to correctly sepa-rate a statement:

printf("The distance between the points is %5.2f \n", distance);

printf("The distance between the points is"

" %5.2f \n",distance);

printf("The distance between the "

"points is %5.2f \n",distance);

Conversion specifiers can be used to make the output of your program readable and us-able.For engineering values, it is also very important to include the corresponding units in the output along with the numerical values.

Although the purpose of the printffunction is to print information, it also returns a value that represents the number of characters printed.

Escape character

Section 2.4 Standard Input and Output 47

Assume that the integer variable sumcontains the value 65, the double variable average contains the value 12.368, and the char variable chcontains the value ‘b’. Show the output line (or lines) generated by the following statements (use bto indicate spaces):

1. printf("Sum = %5i; Average = %7.1f \n", sum, average);

2. printf("Sum = %4i \n Average = %8.4f \n", sum, average);

3. printf("Sum and Average \n\n %d %.1f \n", sum, average);

4. printf("Character is %c; Sum is %c \n", ch, sum);

5. printf("Character is %i; Sum is %i \n", ch, sum);

6. printf("%7.2f is the average; \n", average);

printf("%8d is the sum \n", sum);

7. printf("%7.2f is the average; ", average);

printf("%8d is the sum \n", sum);

P R A C T I C E !

P R A C T I C E !

In document Engineering Problem Solving With C (Page 67-70)