I tried to re-write the itoa() function from K&R exercises, but I failed to define it. I see the answer of the function in the library , but I can't understand what is inside the do block. Please explain it to me. Thanks!
/* itoa: convert n to characters in s */
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);
}
s[i++] = n % 10 + '0';Means:s[i++]means char numberiin char arraysand incrementiby 1n % 10means that you take only the last digit, for example in123,123 % 10returns3which is a digit, this is done to cut your number into digits so you can create a char with each of them.+ '0'means that you add the ascii value of the char'0', for example theint 1 + '0'returns the character'1'so you can get a char array.n /= 10means that we remove the last digit, indeed, we added it to our char array so we can remove it, for example123 / 10 = 12then you can do12 % 10to get the second digit: 2This gives us a char array inverted, for example for 123 we got an array like {'3', '2', '1'} so at the end we call reverse s to (thx captain obvious) reverse our char array
For a negative
nyou can just add a'-'to your char array and multiply yournby-1so it become positive and you can do your job as always :)Hope it helps you :)