Sams Teach Yourself C in 21 Days

(singke) #1

Displaying Information On-Screen ....................................................................


You will want most of your programs to display information on-screen. Two of the most
frequently used ways to do display information are with C’s library functions printf()
andputs().

Theprintf()Function ................................................................................

Theprintf()function is part of the standard C library and is included as a part of the
ANSI standard. It is perhaps the most versatile way for a program to display data on the
screen. You’ve already seen printf()used in many of the examples in this book. Now
you will to see how printf()works.
Printing a text message on the screen is simple. You call the printf()function, passing
the desired message enclosed in double quotation marks. For example, to display How
Now Brown Cow!On the screen, you write
printf(“How Now Brown Cow!”);
In addition to text messages, however, you frequently need to display the value of pro-
gram variables. This is a little more complicated than displaying only a message. For
example, suppose you want to display the value of the numeric variable myNumberon the
screen, along with some identifying text. Furthermore, you want the information to start
at the beginning of a new line. You could use the printf()function as follows:
printf(“\nThe value of myNumber is %d”, myNumber);
The resulting screen display, assuming that the value of myNumberis 12 , would be
The value of myNumber is 12
In this example, two arguments are passed to printf(). The first argument is enclosed in
double quotation marks and is called the format string. The second argument is the name
of the variable (myNumber) containing the value to be printed.

Theprintf()Format Strings ........................................................................

Aprintf()format string specifies how the output is to be formatted. Here are the three
possible components of a format string:


  • Literal textis displayed exactly as entered in the format string. In the preceding
    example, the characters starting with the T(inThe) and up to, but not including, the
    %comprise a literal string.
    •Anescape sequenceprovides special formatting control. An escape sequence con-
    sists of a backslash () followed by a single character. In the preceding example,\n
    is an escape sequence. It is called the newline character,and it means “move to the


148 Day 7

11 448201x-CH07 8/13/02 11:20 AM Page 148

Free download pdf