Step 2 of 6
Printing values with %d
One printf call can print several values. It works through the format string from left to right, and each %d is replaced by the next value in the list after the string, in order.
#include <stdio.h>
int main(void) {
int wins = 7;
int losses = 3;
printf("Record: %d-%d\n", wins, losses);
printf("%d games played\n", wins + losses);
return 0;
}
Record: 7-3
10 games played
Notice that the thing after the comma doesn't have to be a single variable: wins + losses is an expression, and C works out its value (10) before printing it.
The list must match
printf trusts you. It doesn't check that the number of %ds matches the number of values, or that the values really are ints. If they don't match, the output is garbage or the program misbehaves. The compiler usually warns about it (for example more '%' conversions than data arguments), which is one reason to always read warnings.
- Two
%dneed two values, in the order you want them to appear. - Swapping the values swaps the output:
printf("%d-%d\n", losses, wins)prints3-7.
Everything in the format string that isn't a % code is printed as is, including spaces, slashes and punctuation.
Your turn: complete the printf so it prints K/D: 20/5.