Skip to content

Instantly share code, notes, and snippets.

@giuscri
Last active December 24, 2015 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giuscri/6743073 to your computer and use it in GitHub Desktop.
Save giuscri/6743073 to your computer and use it in GitHub Desktop.
Solving EX1-13 of K&R-book
#include <stdio.h>
#define IN 1 // Reading *inside* a word
#define OUT 0 // Reading *outside* a word
int
main()
{
int state = OUT;
int nc = 0;
#define MAX_LENGHT 10
int histo[MAX_LENGHT];
// Inizialize every array-element at 0:
int i;
for (i = 0; i < MAX_LENGHT; ++i)
histo[i] = 0;
int single_byte = getchar();
while (single_byte != EOF) {
switch (state) {
case IN:
if (single_byte != ' ' && single_byte != '\t'
&& single_byte != '\n')
++nc;
else {
state = OUT;
if (nc <= MAX_LENGHT)
++histo[nc -1];
else
++histo[MAX_LENGHT -1];
nc = 0;
}
break;
case OUT:
if (single_byte != ' ' && single_byte != '\t'
&& single_byte != '\n') {
state = IN;
++nc;
}
else
;
break;
}
single_byte = getchar();
}
for (i = 0; i < MAX_LENGHT -1; ++i)
printf("We have %d words of %d characters.\n", histo[i], i +1);
printf("We have %d words of %d or more characters.\n",
histo[MAX_LENGHT -1], MAX_LENGHT);
int max_height = 0;
for (i = 0; i < MAX_LENGHT; ++i)
if (histo[i] >= max_height)
max_height = histo[i];
#define SCALE_VALUE 15
// Normalizing it at SCALE_VALUE pixel:
for (i = 0; i < MAX_LENGHT; ++i)
histo[i] = (int) ((float)histo[i] / (float)max_height * SCALE_VALUE);
// Printing the vertical histogram:
for (i = 0; i < MAX_LENGHT; ++i) {
if (i != MAX_LENGHT -1)
printf(" %2d|", i +1);
else
printf(">%2d|", i +1);
int j;
for (j = 0; j < histo[i]; ++j)
printf("*");
printf("\n");
}
/*
int line_counter = SCALE_VALUE;
while (line_counter >= 0) {
for (i = 0; i < 4; ++i)
if (line_counter <= histo[i])
printf("*");
else
printf(" ");
printf("\n");
--line_counter;
}
*/
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment