As you might expect, printf can also print the values of variables.
Here's an example:
printf("The answer is %d\n", answer);
The arguments to printf are a ``control'' string followed by the
variables whose values you wish to print. The control string describes exactly
how the other arguments to printf should be printed.
Let's examine the control string. The control string itself is printed exactly
as you would expect, until it finds one of the following special sequences:
``%d'' or ``%f''. When printf finds one of those it does
something special:
- ``%d'' tells printf that it should look at the rest of the
arguments that it received. printf takes the next available argument and
prints its value as an integer. (So that next argument has better be an
integer!) The integer argument is ``used up'' by the ``%d'' and won't
be printed again by this printf statement.
- ``%f'' tells printf that it should look at the rest of the
arguments, take the next available one, and print its value as a floating point
number. (So that next argument had better be a floating point number!)
The floating point argument is ``used up'' by the ``%f'' and won't be
printed again by this printf statement.
In short, the special sequences ``%d'' and ``%f'' in the control
string are not themselves printed; instead, the values of the other arguments
to printf are printed in their places. So let's look at our example
again.
printf("The answer is %d\n", answer);
The above printf statement first prints ``The answer is'' and a
space. Then printf finds the special ``%d'' sequence and instead
of printing ``%d'' it prints the value of the (integer) variable
answer. After that, printf finds the ``
n'' and goes on to the
next terminal line.
Figure out for yourself what the following statement does, and then click on
the button below.
printf("At time %d, the velocity is %f.\n", time, velocity);
Click here for the answer.
You should also know that in order to print a `%' you need to write two
percent signs in the control string. For example, the statement:
printf("Please input the %% saturation");
prints the string ``Please input the % saturation''--with only one
percent sign in it.
Eric N. Eide
Hamlet Project
Department of Computer Science
University of Utah