This is an old practice and I am trying to identify where i went wrong with my code: write a c program to print an integer using putchar only. I know one right way to do it is:
void printnumber(int n)
{
if (n < 0) {
putchar('-');
n = -n;
}
if (n == 0)
putchar('0');
if (n/10)
printnumber(n/10);
putchar(n%10 + '0');
}
I just want to know why my way of doing it does not work, though as I was trying to debug using step over, it looks there is no problem with my procedure, however, the code is printing some funny character. I thought it is because putchar() read the number as ascii value and print the character corresponding to ascii value, and maybe this is why in the code above, we are using putchar(n%10+'0')
, so I tried to add '0'
to all my putchar code, but it does not work properly. So here is my code and result without and with '0'
when i=-123
void printnumber(int i)
{
if(i/10!=0)
{
putchar(i%10);
printnumber((i-i%10)/10);
}
else if((i/10==0) && (i%10!=0) && (i>0))
putchar(i%10);
else if((i/10==0) && (i%10!=0) && (i<=0))
putchar(-i%10);
}
if(i/10!=0)
{
putchar(i%10);
printnumber((i-i%10)/10);
}
If i < 0
, then the first putchar()
is in trouble no matter you + '0'
or not.