:: Re: [DNG] [OT] [Re: Studying C as t…
Startseite
Nachricht löschen
Nachricht beantworten
Autor: Edward Bartolo
Datum:  
To: dng
Betreff: Re: [DNG] [OT] [Re: Studying C as told. (For help)
Hi,

This is NOT a difficulty. I am posting my code so that anyone wanting
to comment can do so.

Pg 38, Exercise: 1-13
Write a program to print a histogram of the lengths of words in its
input. Horizontal bars selected.

My solution/code:

#include <stdio.h>

int main() {
#define MAX_LENGTH 10


int word_sizes[MAX_LENGTH];

  int i;
  for (i = 0; i < MAX_LENGTH; ++i)
    word_sizes[i] = 0;


  /* fill in the frequencies array, word_sizes */
  char c;
  int ws = 0;
  while ((c = getchar()) != EOF) {
    if (c == ' ' || c == '\n' || c == '\t') {
        if (ws > 0) {
          if (ws > MAX_LENGTH) {
            printf("\nMAX_LENGTH execeeded, exiting.\n");
            return -1;
          }
          ++word_sizes[ws];
        }
        ws = 0;
      }
    else ++ws;
  }


  /* display the histogram */
  int j;
  for (i = 0; i < MAX_LENGTH; ++i) {
    printf("%d chars\t", i);
    for (j = 1; j <= word_sizes[i]; ++j)
      printf("#");
    printf("\n");
  }


return 0;
}

Edward