|
1 | 1 | /*
|
2 | 2 | * Exercise 4-13. Write a recursive version of the function reverse(s), which
|
3 | 3 | * reverses the string s in place.
|
| 4 | + * |
4 | 5 | * By Faisal Saadatmand
|
5 | 6 | */
|
6 | 7 |
|
7 | 8 | #include <stdio.h>
|
8 | 9 | #include <string.h>
|
9 |
| -#include <limits.h> |
| 10 | + |
| 11 | +#define MAXLEN 1000 |
10 | 12 |
|
11 | 13 | /* functions */
|
12 | 14 | void reverse(char []);
|
13 |
| -void itoa(int, char []); |
14 | 15 |
|
15 | 16 | /* reverse function: reverse string s in place, recursive version */
|
16 | 17 | void reverse(char s[])
|
17 | 18 | {
|
18 |
| - int c, j; |
19 |
| - static int i; |
20 |
| - |
21 |
| - j = (strlen(s) - 1) - i; |
22 |
| - if (j >= 0) { |
23 |
| - c = s[i]; |
24 |
| - s[i++] = s[j]; |
25 |
| - s[j] = c; |
| 19 | + int c; |
| 20 | + static unsigned long i = 0, j = 0; |
| 21 | + |
| 22 | + if (j < strlen(s) - 1) { |
| 23 | + ++j; |
26 | 24 | reverse(s);
|
27 | 25 | }
|
28 |
| -} |
29 |
| - |
30 |
| -/* itoa: convert n to characters in s */ |
31 |
| -void itoa(int n, char s[]) |
32 |
| -{ |
33 |
| - int i, sign, lastDigit; |
34 |
| - |
35 |
| - lastDigit = 0; |
36 |
| - if (n == INT_MIN) { /* add check for size */ |
37 |
| - lastDigit = (n % 10 * -1) + '0'; /* extract save the last digit */ |
38 |
| - n -= 1; /* reduce n to fit INT_MAX */ |
| 26 | + if (i < j) { |
| 27 | + c = s[i]; |
| 28 | + s[i++] = s[j]; |
| 29 | + s[j--] = c; |
39 | 30 | }
|
40 |
| - |
41 |
| - if ((sign = n) < 0) /* record sign */ |
42 |
| - n = -n; |
43 |
| - |
44 |
| - i = 0; |
45 |
| - do { /* generate digits in reverse order */ |
46 |
| - s[i++] = n % 10 + '0'; /* get next digit */ |
47 |
| - } while ((n /= 10) > 0); |
48 |
| - |
49 |
| - if (sign < 0) |
50 |
| - s[i++] = '-'; |
51 |
| - |
52 |
| - if (lastDigit > 0) /* put back saved last digit */ |
53 |
| - s[0] = lastDigit; |
54 |
| - |
55 |
| - s[i] = '\0'; |
56 |
| - |
57 |
| - reverse(s); |
58 | 31 | }
|
59 | 32 |
|
60 | 33 | int main(void)
|
61 | 34 | {
|
62 |
| - int intValue; |
63 |
| - char stringNumber[64]; |
64 |
| - |
65 |
| - printf("Enter integer to convert to a string: "); |
66 |
| - scanf("%i", &intValue); |
67 |
| - |
68 |
| - itoa(intValue, stringNumber); |
| 35 | + char str[MAXLEN]; |
69 | 36 |
|
70 |
| - printf("%s\n", stringNumber); |
| 37 | + printf("Enter a string to reverse:\n"); |
| 38 | + scanf("%s", str); |
| 39 | + reverse(str); |
| 40 | + printf("%s\n", str); |
71 | 41 |
|
72 | 42 | return 0;
|
73 | 43 | }
|
0 commit comments