5

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 ?

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
user182502
  • 23
  • 3

3 Answers3

12

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Erich
  • 3,946
  • 1
  • 22
  • 21
2

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

The call to reverse() fixes this.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • yh but what i want to know how its pulling numbers from behind ? by modulus operator ? – user182502 Oct 02 '09 at 18:54
  • also if it does why since it just get the remainder i did the math the remainder is always after the . is that last number in the number but i don't know why dunno i m somewhat confused – user182502 Oct 02 '09 at 19:07
1

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.

Clifford
  • 88,407
  • 13
  • 85
  • 165