In this article, we used printf to print the value of a string constant (that is, the characters of the string excluding the quotes). We now show how we can print the value of a variable ignoring, for the moment, how the variable gets its value. Suppose the integer variable a has the value 52. The statement:
printf("The number of students = %d\n", a);
will print:
The number of students = 52
This printf is a bit different from those we have seen so far. This one has two arguments—a string and a variable. The string, called the format string, contains a format specification %d. In our previous examples, the format string contained no format specifications.
The effect, in this case, is that the format string is printed as before, except that the %d is replaced by the value of the second argument, a. Thus, %d is replaced by 52, giving:
>The number of students = 52
We will explain printf and format specifications in more detail later but, for now, note that we use the specification %d if we want to print an integer value.
What if we want to print more than one value? This can be done provided that each value has a corresponding format specification. For example, suppose that a has the value 14 and b has the value 25. Consider,
printf("The sum of %d and %d is %d\n", a, b, a + b);
This printf has four arguments—the format string and three values to be printed: a, b and a + b. The format string must contain three format specifications: the first will correspond to a, the second to b and the third to a + b. When the format string is printed, each %d will be replaced by the value of its corresponding argument, giving:
The sum of 14 and 25 is 39
Exercise: What is printed by the following statement?
printf("%d + %d = %d\n", a, b, a + b);