Exercise 1-13 Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging
#include<stdio.h>
#define MAXWORD 100
void HorizontalDraw(const int len[], int nw){ int i, n; for(i = 0; i < nw; i++){ n = len[i]; while(n > 0){ putchar('*'); n--; } putchar('\n'); } }
void VerticalDraw(const int len[], int nw){ int i, max; for(max = 0, i = 0; i < nw; i++) if(max < len[i]) max = len[i]; while(max > 0){ for(i = 0; i < nw; i++) if(len[i] >= max) putchar('*'); else putchar(' '); putchar('\n'); max--; } }
int main(){ int c, state, i; int len[MAXWORD];
state = 0; i = -1; while((c = getchar()) != EOF){ if(c == ' ' || c == '\t' || c == '\n') state = 0; else if(state == 0){ state = 1; i++; len[i] = 1; }else len[i]++; }// i+1 words
VerticalDraw(len, i + 1); }
|
阅读(372) | 评论(0) | 转发(0) |