printf
function
Before using printf
you need to
#include<stdio.h>
.
The first argument to printf
function is a string of
characters which is called 'format string' or 'template'. If it
is the only argument, this string is simply printed to the standard
output (which by default is your terminal). For example,
printf("hello\n");
hellowhere the string
\n
represents the newline character.
Besides the first argument --- the format string --- printf
can have more arguments which then must be the names of the variables
(or expressions) which you want to print out. In this case the
format string must contain placeholders for the arguments to be
printed. The string is then printed with placeholders being replaced by
the values of the given variables (expressions).
By default the first argument after the format string takes the first placeholder, the second argument after the format string takes the second placeholder and so on.
Placeholders must correspond to the types of arguments to be printed!
We shall mostly print out numbers, therefore here are the simplest forms of placeholders for numbers,
%i
For example
int n=123; printf("n = %i, twice n = %i, five times n = %i \n", n, 2*n, 5*n);
produces
n = 123, twice n = 246, five times n = 615
%g
(actually %lg
but %g
seems to work somehow)
For example
double x=1.23; printf("x = %g, twice x = %g, five times x = %g \n", x, 2*x, 5*x);
produces
x = 1.23, twice x = 2.46, five times x = 6.15
%Lg
The full description of format placeholders can be found
in
wikipedia or in the man pages man 3 printf
.