Added example with variable arrays.
[C-Programming-Examples.git] / ex_4-12.c
blob7d35c63aa127b7c73bbc0382ad6d17db4b0e55c1
1 #include <string.h>
2 #include <stdio.h>
4 /* print contents of array */
5 void print_array(char s[])
7 int i;
8 for(i = 0; i < strlen(s); i++)
9 printf("%c", s[i]);
10 printf("\n");
13 /* reverse contents of array in place */
14 void reverse_array(char s[])
16 int c, i, j;
17 for(i = 0, j = strlen(s)-1; i < j; i++, j--)
19 c = s[i];
20 s[i] = s[j];
21 s[j] = c;
25 /* convert int n into chars in s[] - page 64*/
26 void itoa(int n, char s[])
28 int i, sign;
30 if((sign = n) < 0) // record sign
31 n = -n; // reverse sign
32 i = 0;
33 do { // generates digits in reverse order
34 s[i++] = n % 10 + '0'; // get next digit and load into array
35 } while ((n /= 10) > 0); // delete each digit as we move along
36 if(sign < 0)
37 s[i++] = '-';
38 s[i] = '\0';
39 reverse_array(s);
42 /* recursive version of itoa - book has not covered pointers yet :( */
43 int itoa_rec(int n, char s[], int i)
45 if(n < 0)
47 s[i++] = '-';
48 n = -n;
50 if(n / 10)
51 i = itoa_rec(n/10, s,i);
53 s[i++] = (n % 10 + '0');
54 s[i] = '\0';
55 return i;
58 int main()
60 char s[10]; // must have plenty of space here...
61 int n = -1024;
63 itoa(n, s);
64 print_array(s);
66 itoa_rec(n, s, 0);
67 print_array(s);
68 return 1;