putchar
expects a character code as its input. The character codes for digits from 0
to 9
may vary in different encodings, but they almost always come sequentially (including in ASCII). This means that if you have the digit n
and want to get the corresponding character, the simplest way to acheive that is to add the character code of '0'
to it. (Character codes in C are represented by the char
type, and treated like regular numbers, so addition is perfectly valid for them. However, it's important to realize that, in most all C-compatible encodings, '0'
's character code is not 0. In ASCII in particular, it's 48. But it's more comprehensible and universal to write '0'
than 48
)
Note that it, obviously, only works for singe digits, though.
EDIT: Fixed according to the comments