|
2 | 2 | * Exercise 4-12: Adapt the idea of printd to write a recursive version of
|
3 | 3 | * itoa; that is, convert an integer into a string by calling a recursive
|
4 | 4 | * routine.
|
| 5 | + * |
5 | 6 | * By Faisal Saadatmand
|
6 | 7 | */
|
7 | 8 |
|
| 9 | +/* |
| 10 | + * NOTE: We could have made i a static variable; however, that is problematic |
| 11 | + * because its value will persists throughout the entire life of the program, and |
| 12 | + * thus, multiple calls to itoa will use the value of i from the previous call, |
| 13 | + * which will result in an undesirable outcome. |
| 14 | + */ |
| 15 | + |
8 | 16 | #include <stdio.h>
|
9 | 17 | #include <string.h>
|
10 | 18 | #include <limits.h>
|
11 | 19 |
|
| 20 | +#define MAXLEN 1000 |
| 21 | + |
12 | 22 | /* functions */
|
13 |
| -void itoa(int, char []); |
| 23 | +int itoa(unsigned, char [], int); |
14 | 24 |
|
15 |
| -/* itoa: convert n to characters in s. Recursive version */ |
16 |
| -void itoa(int n, char s[]) |
| 25 | +int itoa(unsigned n, char s[], int i) |
17 | 26 | {
|
18 |
| - int lastDigit; |
19 |
| - int static i; /* note static type */ |
20 |
| - |
21 |
| - lastDigit = 0; |
22 |
| - if (n == INT_MIN) { /* add check for minimum signed int */ |
23 |
| - lastDigit = (n % 10 * -1) + '0'; /* extract and save the last digit */ |
24 |
| - n += 1; /* reduce n to fit into INT_MAX */ |
25 |
| - } |
| 27 | + int sign; |
26 | 28 |
|
27 |
| - if (n < 0) { |
28 |
| - s[i++] = '-'; /* store leading negative sign */ |
| 29 | + if ((sign = n) < 0) { |
| 30 | + s[i++] = '-'; |
29 | 31 | n = -n;
|
30 | 32 | }
|
31 |
| - |
32 | 33 | if (n / 10)
|
33 |
| - itoa(n / 10, s); /* recursive call */ |
34 |
| - |
| 34 | + i = itoa(n / 10, s, i); /* recursive call */ |
35 | 35 | s[i++] = n % 10 + '0';
|
36 |
| - |
37 |
| - if (lastDigit > 0) { |
38 |
| - --i; |
39 |
| - s[i++] = lastDigit; /* put back saved last digit */ |
40 |
| - } |
41 |
| - |
42 | 36 | s[i] = '\0';
|
| 37 | + return i; /* return the updated value of i */ |
43 | 38 | }
|
44 | 39 |
|
45 | 40 | int main(void)
|
46 | 41 | {
|
47 |
| - int intValue; |
48 |
| - char stringNumber[64]; |
| 42 | + char str[MAXLEN]; |
| 43 | + |
| 44 | + itoa(996, str, 0); |
| 45 | + printf("%s\n", str); |
49 | 46 |
|
50 |
| - printf("Enter integer to convert to a string: "); |
51 |
| - scanf("%i", &intValue); |
| 47 | + itoa(-2345, str, 0); |
| 48 | + printf("%s\n", str); |
52 | 49 |
|
53 |
| - itoa(intValue, stringNumber); |
| 50 | + itoa(INT_MAX, str, 0); |
| 51 | + printf("%s\n", str); |
54 | 52 |
|
55 |
| - printf("%s\n", stringNumber); |
| 53 | + itoa(INT_MIN, str, 0); |
| 54 | + printf("%s\n", str); |
56 | 55 |
|
57 | 56 | return 0;
|
58 | 57 | }
|
0 commit comments