Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* K&R Ex 4-12. Adapt the idea of printd to write a recursive version of itoa;
- * that is, convert an integer into a string by calling a recursive routine. */
- #include <stdio.h>
- int itoa_recursive(int, char[]);
- int main() {
- char s[1000];
- int n1 = -345;
- int n2 = 35532;
- itoa_recursive(n1, s);
- printf("%s\n", s);
- itoa_recursive(n2, s);
- printf("%s\n", s);
- return 0;
- }
- int itoa_recursive(int n, char s[]) {
- int i;
- if (n / 10) {
- i = itoa_recursive(n / 10, s);
- if (s[0] == '-') {
- s[i++] = -n % 10 + '0';
- } else {
- s[i++] = n % 10 + '0';
- }
- s[i] = '\0';
- return i;
- } else {
- i = 0;
- if (n < 0) {
- s[i++] = '-';
- s[i++] = -n % 10 + '0';
- } else {
- s[i++] = n % 10 + '0';
- }
- s[i] = '\0';
- return i;
- }
- }
Add Comment
Please, Sign In to add comment