Guest User

Untitled

a guest
Nov 17th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.92 KB | None | 0 0
  1. /* K&R Ex 4-12. Adapt the idea of printd to write a recursive version of itoa;
  2.  * that is, convert an integer into a string by calling a recursive routine. */
  3.  
  4. #include <stdio.h>
  5.  
  6. int itoa_recursive(int, char[]);
  7.  
  8. int main() {
  9.  
  10.     char s[1000];
  11.     int n1 = -345;
  12.     int n2 = 35532;
  13.  
  14.     itoa_recursive(n1, s);
  15.     printf("%s\n", s);
  16.     itoa_recursive(n2, s);
  17.     printf("%s\n", s);
  18.  
  19.     return 0;
  20. }
  21.  
  22. int itoa_recursive(int n, char s[]) {
  23.  
  24.     int i;
  25.  
  26.     if (n / 10) {
  27.         i = itoa_recursive(n / 10, s);
  28.         if (s[0] == '-') {
  29.             s[i++] = -n % 10 + '0';
  30.         } else {
  31.             s[i++] = n % 10 + '0';
  32.         }
  33.         s[i] = '\0';
  34.         return i;
  35.     } else {
  36.         i = 0;
  37.         if (n < 0) {
  38.             s[i++] = '-';
  39.             s[i++] = -n % 10 + '0';
  40.         } else {
  41.             s[i++] = n % 10 + '0';
  42.         }
  43.         s[i] = '\0';
  44.         return i;
  45.     }
  46. }
Add Comment
Please, Sign In to add comment