Printing values, not just fixed text
The percent signs that mark where a number goes, and the count printf hands back when it is done.
Everything printed so far has been fixed: the same characters every time, whatever the program has worked out. That is not much use on its own. printf's real job is to drop values into the text, a count, a price, a name, and to do that you need a way of marking where the value should go.
You mark the place with a conversion specification, which begins with a percent sign, and you pass the value after the format string.
That needs somewhere for the value to come from, so here is the one sentence about variables this lesson needs. int apples = 3; creates a named place in memory called apples, of type int, which is C's ordinary whole number, and puts 3 in it. Types are the whole of the next section.
Change %.2f to %.0f and run it again, then to %.5f. The value sitting in price never changes; only the way printf writes it down does.
double is C's number with a fractional part, and %f is how printf writes one. %.2f says the same thing with two digits after the point. A handful of specifications covers almost everything you will print in your first month.
| Specification | Prints | Example |
|---|---|---|
%d | an int, in decimal | printf("%d", 42) gives 42 |
%lld | a long long, C's wider whole number | printf("%lld", 42LL) gives 42 |
%f | a double, six digits after the point | printf("%f", 1.5) gives 1.500000 |
%.2f | a double, two digits after the point | printf("%.2f", 1.5) gives 1.50 |
%s | a piece of text | printf("%s", "Ada") gives Ada |
%c | one character | printf("%c", 'A') gives A |
%% | a percent sign | printf("100%%") gives 100% |
Several specifications can appear in one format string. printf works through the text from left to right and takes the next value each time it meets one, so the order of the values has to match the order of the specifications exactly.
Change both 17s to 13 and run it again. Then change %.1f to %.3f and watch how much more of the answer you are shown.
One last detail, because it makes the point that everything in C hands something back. printf itself returns a value: the number of characters it managed to write. Almost nobody looks at it, but it is there, and looking at it once tells you exactly how printf counts.
Add a word to the first text and run it again. Does the count go up by exactly the number of letters you typed?
How many characters does printf("Hi\n") report writing?
Three. H, i, and the new line. The backslash and the n are two keystrokes in your source file but one character in the output, which is the whole point of an escape sequence: it is how you write a character that has no key of its own.