I don't understand itoa() in K&R book

1.7k Views Asked by At

I am reading K&R; so far I'm doing well with it, but there is something in function itoa() which I don't understand. Here in itoa() they say they reverse the numbers themselves. For example 10 is 01 (they reverse the string):

void itoa(int n, char s[])
{
    int i, sign;
    if ((sign = n) < 0) /* record sign */
        n = -n; /* make n positive */
    i = 0;
    do { /* generate digits in reverse order */
        s[i++] = n % 10 + '0'; /* get next digit */
    } while ((n /= 10) > 0); /* delete it */
    if (sign < 0)
        s[i++] = '-';
    s[i] = '\0';
    reverse(s);
    return;
}

I don't understand how it reversed the number. Even though we are just doing n % 10 + '0' then its the following digit which 10 then 1 gets deleted then it goes to 0 right ? Or I don't get its logic ?

3

There are 3 best solutions below

0
On BEST ANSWER

In the do-while loop, it is pulling the numbers off from behind (the least significant digit first). So, if you had the number -123456789, it processes the 9, then the 8, then the 7, etc.

So, when it hits the null-terminator (3rd to last line), you would have "987654321-", which is then reversed.

2
On

n % 10 gives 0 for n = 10, so after the loop, the string s contains 01.

The call to reverse() fixes this.

0
On

The algorithm determines the digits from least to most significant order. Because the total number of digits that will be generated is not known in advance, the correct position cannot be determined as they are generated - the least significant digit will be at the end, but the 'end' is not known. So they are buffered in the order they are calculated (reverse) and then the whole string is reversed to correct the ordering.

One way of avoiding this is to determine the length in advance:

decimal_digits = (int)log10( n ) + 1 ;

but on devices without an FPU (and some with very simple FPUs) that is likely to be a heavier task than string reversal.