A Few Words about printf

The VOLUME.C program, like most examples in this book, uses the printf library function to display text. You won't need to know all of the details of printf to read the rest of this book, but the examples will be easier to follow if you know a few basic concepts.

The printf function works like the QuickBasic PRINT USING statement or the QuickPascal Writeln procedure. It can display string and numeric data in various formats, and it normally prints to the screen.

You can print a simple message by passing printf a string (characters in double quotes) as an argument:

printf( "Hi, Mom!" );

The statement prints

Hi, Mom!

The printf function doesn't automatically add a newline character at the end of a line. The statements

printf( "Le Nozze di Figaro" );

printf( " by W. A. Mozart" );

print the following message on one line:

Le Nozze di Figaro by W. A. Mozart

To start a new line, use the escape sequence \n as follows:

printf( "Hi,\nMom!" );

The statement prints the two words on separate lines:

Hi,

Mom!

The f in printf stands for formatting. To print the values of variables and other items, you supply printf with format codes that tell printf the proper format for each item. The codes are placed in the first argument, which is enclosed in double quotes.

The following statement uses the %x code to print the integer 553 in hexadecimal format. It passes two arguments to printf:

printf( "%x", 553 );

The first argument ("%x") contains the format code and the second argument (553) contains the item to be formatted. The line displays the following:

229

The printf function accepts several other format codes. For instance, the VOLUME.C program uses %f to print a floating-point number. Some programs in later chapters use %d to print integers or %ld to print long integers.

The first argument passed to printf can contain any combination of characters and format codes. The other arguments contain the items that you want printf to format. The statement

printf( "%d times %d = %d\n", 2, 128, 2 * 128 );

prints the line:

2 times 128 = 256

The printf function matches the format codes to the items you want to format, in left-to-right order. In the code above, the first %d formats the number 2, the second formats the 128, and the third formats the expression 2 * 128 (which evaluates to the number 256).

There's much more to say about printf and other I/O functions, but the rest can wait until you reach Chapter 11, “Input and Output,” which describes I/O in detail.

Now that you've glimpsed the big picture, we can take a closer look at some specifics of C programming, beginning with Chapter 2, “Functions.”