L-1 MCS 275 Mon 8 Jan 2001
Below are listings for programs we discussed in class.
/* make a frequency table for floats */
#include <stdio.h>
int main(void)
{
float x;
int i;
int freq[12];
/* freq[0] counts numbers x for which 0.0 <= x < 0.1,
freq[1] counts numbers x for which 0.1 <= x < 0.2,
freq[2] counts numbers x for which 0.2 <= x < 0.3, ... ,
freq[10] counts numbers x for which 1.0 <= x,
freq[11] counts numbers x for which x < 0.0. */
printf("Give sequence of floats :\n");
for (i=0; i<12; ++i) freq[i] = 0;
while (scanf("%f", &x) == 1)
{
if (x < 0.0)
++freq[11];
else if (x >= 1.0)
++freq[10];
else
{
i = 10*x; /* type cast truncates */
++freq[i];
}
}
printf("The frequency table :\n");
for (i=0; i<12; ++i) printf("%5d",freq[i]);
printf("\n");
return 0;
}
This is the version with pointers, avoiding arrays entirely.
/* make a frequency table for floats, pointer version */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
float x;
int i;
int *freq, *p;
/* freq[0] counts numbers x for which 0.0 <= x < 0.1,
freq[1] counts numbers x for which 0.1 <= x < 0.2,
freq[2] counts numbers x for which 0.2 <= x < 0.3, ... ,
freq[10] counts numbers x for which 1.0 <= x,
freq[11] counts numbers x for which x < 0.0. */
printf("Give sequence of floats :\n");
freq = calloc(12, sizeof(int));
while (scanf("%f", &x) == 1)
{
if (x < 0.0)
++(*(freq+11));
else if (x >= 1.0)
++(*(freq+10));
else
{
i = 10*x; /* type cast truncates */
++(*(freq+i));
}
}
printf("The frequency table :\n");
p = freq;
for (i=0; i<12; ++i)
{
printf("%5d",*p);
++p;
}
printf("\n");
free(freq);
return 0;
}