Skip to content

Commit 6baec96

Browse files
committed
refined answer
1 parent dc5f5e6 commit 6baec96

File tree

1 file changed

+27
-28
lines changed

1 file changed

+27
-28
lines changed

chapter04/4-12.c

Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2,57 +2,56 @@
22
* Exercise 4-12: Adapt the idea of printd to write a recursive version of
33
* itoa; that is, convert an integer into a string by calling a recursive
44
* routine.
5+
*
56
* By Faisal Saadatmand
67
*/
78

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+
816
#include <stdio.h>
917
#include <string.h>
1018
#include <limits.h>
1119

20+
#define MAXLEN 1000
21+
1222
/* functions */
13-
void itoa(int, char []);
23+
int itoa(unsigned, char [], int);
1424

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)
1726
{
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;
2628

27-
if (n < 0) {
28-
s[i++] = '-'; /* store leading negative sign */
29+
if ((sign = n) < 0) {
30+
s[i++] = '-';
2931
n = -n;
3032
}
31-
3233
if (n / 10)
33-
itoa(n / 10, s); /* recursive call */
34-
34+
i = itoa(n / 10, s, i); /* recursive call */
3535
s[i++] = n % 10 + '0';
36-
37-
if (lastDigit > 0) {
38-
--i;
39-
s[i++] = lastDigit; /* put back saved last digit */
40-
}
41-
4236
s[i] = '\0';
37+
return i; /* return the updated value of i */
4338
}
4439

4540
int main(void)
4641
{
47-
int intValue;
48-
char stringNumber[64];
42+
char str[MAXLEN];
43+
44+
itoa(996, str, 0);
45+
printf("%s\n", str);
4946

50-
printf("Enter integer to convert to a string: ");
51-
scanf("%i", &intValue);
47+
itoa(-2345, str, 0);
48+
printf("%s\n", str);
5249

53-
itoa(intValue, stringNumber);
50+
itoa(INT_MAX, str, 0);
51+
printf("%s\n", str);
5452

55-
printf("%s\n", stringNumber);
53+
itoa(INT_MIN, str, 0);
54+
printf("%s\n", str);
5655

5756
return 0;
5857
}

0 commit comments

Comments
 (0)