Added example cbd_rand_dist. Generates random numbers and displays distribution.
[C-Programming-Examples.git] / srs_lib.c
blob14c7835c491e7ee38c4809fe56704f1dac6e65a0
1 #include <stdio.h>
2 #include <string.h>
4 #include "srs_lib.h"
6 /* print contents of array */
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 /* print contents of array */
16 void print_sparse_array(char s[][MAXLEN])
18 int i, j;
19 for(i = 0; i < MAXLINES; i++)
21 int found = 0;
22 for(j = 0; j < MAXLEN; j++)
24 if(s[i][j] != '\0') { found++; }
26 if(found > 0)
28 printf("%d:\t", i);
29 for(j = 0; j < MAXLEN; j++)
30 printf("%c", s[i][j]);
31 printf("\n");
34 printf("\n");
37 /* reverse contents of array in place */
38 void reverse(char s[])
40 int c, i, j;
41 for(i = 0, j = strlen(s)-1; i < j; i++, j--)
43 c = s[i];
44 s[i] = s[j];
45 s[j] = c;
49 /* convert integer to another base and store result in array of char */
50 int itob(int n, char s[], int b)
52 int sign, i = 0;
54 //create string of digits used to represent chars
55 char base_chars[] = { "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" };
57 //check that base is neither too high nor too small
58 if(b < 2)
60 printf("Base must be between 2 and %d.\n", (int)strlen(base_chars)-1);
61 return -1;
64 if(b > strlen(base_chars)-1)
66 printf("Base must be %d or less.\n", (int)strlen(base_chars)-1);
67 return -1;
70 // remove sign from number
71 if(n < 0) { n = -n; sign = 1; }
74 // increment s array and store in that location the modulus of the number -vs- the base
75 // while number divided by base is larger than 0
76 i = 0;
77 do {
78 s[i++] = base_chars[n % b];
79 } while ((n /= b) > 0);
81 // add sign from above
82 if(sign == '1') { s[++i] = '-'; }
83 s[i] = '\0';
85 reverse(s);
86 return 1;