Adapt the ideas of
printd
to write recursive version ofitoa
; that is, convert integer into a string by calling a recursive routine
Here is the implementation of printd:
void printd(int n) {
if(n < 0)
putchar('-');
if(n / 10)
printd(n / 10);
putchar(n % 10 + '0')l
}
And here is my solution:
int itoa(int n, char s[]) {
int i;
if(n < 0) {
n *= -1;
}
i = 0;
if(n / 10) {
i = itoa(n / 10, s);
}
s[i] = n % 10 + '0';
s[++i] = '\0';
return i; /* next free slot in array */
}
As you can see, my version of itoa
is a little bit different than the one presented in the book. It returns a variable i
that represents the index of the next free slot in array, at every step it fills the next empty slot with the null character. At the deepest level of recursion, it returns 1.
Could you review my exercise?