Added exmaple cbd_pennies_adv. Now calculates final value in dollars.
[C-Programming-Examples.git] / ex_3-5.c
blob6608f0097b27d121270c1cf4526722a4f3546d39
1 #include <stdio.h>
2 #include <string.h>
4 int itob(int n, char s[], int b);
5 void reverse(char s[]);
7 void print_array(char s[])
9 int i;
10 for(i = 0; i < strlen(s); i++)
11 printf("%c", s[i]);
12 printf("\n");
15 //main displays same number from base of two to highest base
16 int main()
19 int base, number = 16384;
20 char ans[255] = { '\0' };
21 for(base = 2; base < 62; ++base)
23 if(itob(number, ans, base))
25 printf("Number: %d\tBase: %d Ans: ", number, base);
26 print_array(ans);
29 return 0;
32 int itob(int n, char s[], int b)
34 int sign, i = 0;
36 //create string of digits used to represent chars
37 char base_chars[] = { "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" };
39 //check that base is neither too high nor too small
40 if(b < 2)
42 printf("Base must be between 2 and %d.\n", (int)strlen(base_chars)-1);
43 return -1;
46 if(b > strlen(base_chars)-1)
48 printf("Base must be %d or less.\n", (int)strlen(base_chars)-1);
49 return -1;
52 // remove sign from number
53 if(n < 0) { n = -n; sign = 1; }
56 // increment s array and store in that location the modulus of the number -vs- the base
57 // while number divided by base is larger than 0
58 i = 0;
59 do {
60 s[i++] = base_chars[n % b];
61 } while ((n /= b) > 0);
63 // add sign from above
64 if(sign == '1') { s[++i] = '-'; }
65 s[i] = '\0';
67 reverse(s);
68 return 1;
71 // reverse string created (it was created in reverse order)
72 void reverse(char s[])
74 int temp, i, j;
75 for(i = 0, j = strlen(s)-1; j > i; i++, j--)
77 temp = s[i];
78 s[i] = s[j];
79 s[j] = temp;