/* Copyright (c) 1996, SAS Institute Inc. */ /* Unpublished - All Rights Reserved */ /* Language: C */ /* Simple word counting program. This program provides */ /* three types of statistical output on any given file(s) */ /* 1) total words, 2) average length, and 3) mdeian length*/ /* */ #include <stdio.h> #include <ctype.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 #define MAXLEN 32 /* Maximum length of a word */ void readin(FILE *); void stats(int, int, int *); /*------------------MAIN------------------------------*/ /* Open input file. Call readin */ /* */ void main() { FILE *input; /* input file */ /* open input file */ if ((input = fopen("ddn:DATAIN","r")) != NULL) readin(input); else { fprintf(stderr,"Error: cannot open input file\n"); exit(1); } exit(0); } /*------------------READIN----------------------*/ /* Read in words from input file and compute */ /* stats. Call stats to print stat output. */ /* */ void readin(f) FILE *f; { int totalwords=0,lengthsum=0,wordlen=0, wordcnt(|MAXLEN|), /* counter for each length total */ i,c,inword=FALSE; /* initialize wordcnt */ for(i=0;i<MAXLEN;i++) wordcnt(|i|)=0; /* Read in each word from input */ /* Get a character-if alphabetic */ /* set inword to TRUE. Test */ /* wordlen. Increment wordlen. */ while((c=fgetc(f)) != EOF) { if (isalpha(c)) { inword=TRUE; if (wordlen < MAXLEN) wordlen++; } else if (inword == TRUE) { /* Compute stats for each new word */ /* If the character is not alpha- */ /* betic and inword = TRUE, */ /* increment wordcnt, totalwords, */ /* lengthsum. Set wordlen to 0; */ /* inword to false. */ wordcnt(|wordlen-1|)++; totalwords++; lengthsum+=wordlen; wordlen=0; inword=FALSE; } } stats(lengthsum,totalwords,wordcnt); } /*------------------STATS--------------------------*/ /* compute and print final stats on the data */ /* gathered in "readin" */ /* */ void stats(int lengthsum, int totalwords, int wordcnt(||)) { double average=0; int halfwords,median,i,j,count; if(totalwords > 0) { /* Compute the mean */ average=((double)lengthsum)/totalwords; /* Compute median value */ halfwords = totalwords/2; for(i=0,count=0;count <= halfwords;i++) count+=wordcnt(|i|); /* if even number of words */ if(totalwords % 2 == 0) { for(j=0,count=0;count < halfwords;j++) count+=wordcnt(|j|); median=(i+j)/2; } /* else odd number of words */ else median=i; } /* display the statistics */ printf("Totalwords: %d\n",totalwords); printf("Average length: %4.3f\n",average); printf("Median: %d\n\n",median); }