Reputation: 129
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);
}
Upvotes: 1
Views: 10238
Reputation: 206577
The first version works like a charm for me.
Here's the function with main
.
#include <stdio.h>
#include <stdlib.h>
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');
}
int main(int argc, char** argv)
{
int n = atoi(argv[1]);
printnumber(n);
printf("\n");
}
Here's some output:
~/Stack-Overflow/cpp>>./test-44 Segmentation fault ~/Stack-Overflow/cpp>>./test-44 10 10 ~/Stack-Overflow/cpp>>./test-44 3456789 3456789 ~/Stack-Overflow/cpp>>./test-44 -10 -10 ~/Stack-Overflow/cpp>>./test-44 -95823 -95823 ~/Stack-Overflow/cpp>>
PS. I am testing on Linux, using gcc 4.7.3.
Now about the second approach...
'0'
to the integer value in the call to putchar
is absolutely needed.if
block and the last else if
block, you have take care of -ve numbers.0
is still an issue.if
block, recursion has to be before the print. Otherwise, you will end up printing the digits in the reverse order.Here's what I came up with:
void printnumber(int i)
{
if(i/10!=0)
{
printnumber(i/10);
if ( i > 0 )
{
putchar(i%10 + '0');
}
else
{
putchar(-i%10 + '0');
}
}
else if((i/10==0) && (i%10!=0) && (i>0))
{
putchar(i%10 + '0');
}
else if((i/10==0) && (i%10!=0) && (i<=0))
{
putchar('-');
putchar(-i%10+'0');
}
}
PS. My version continues to have a problem with the number 0. It doesn't print anything.
Upvotes: 3
Reputation: 23058
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.
Upvotes: 1