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 number i
in char array s
and increment i
by 1n % 10
means that you take only the last digit, for example in 123
, 123 % 10
returns 3
which 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 the int 1 + '0'
returns the character '1'
so you can get a char array.n /= 10
means that we remove the last digit, indeed, we added it to our char array so we can remove it, for example 123 / 10 = 12
then you can do 12 % 10
to 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 n
you can just add a '-'
to your char array and multiply your n
by -1
so it become positive and you can do your job as always :)
Hope it helps you :)