Search code examples
carraysprintfhistogram

What ways (using stdio) can I print a vertical histogram


I'm doing all the K&R exercises and I have finally been able to print a horizontal histogram. It look awful too, but I'll let you judge it. I have not been able to print a histogram of the lengths of words in its input vertically.

How can I modify my program to do this?

Question: Write a program to print a histogram of the lengths if words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging.

histogram.c

#include <stdio.h>
#define MAX 10
#define IN 1
#define OUT 0

int main()
{
    int c, len, state;
    int nlength[MAX];
    c = len = 0;
    state = 1;

    for(int i = 0; i < 10; ++i) 
        nlength[i] = 0;

    while ((c = getchar()) != EOF) {
        ++len;
        if (c == ' ' || c == '\n' || c == '\t') {
            --len;
            state = OUT;
        }
            if(state == OUT) {
                if(len != 0 && len <= MAX)
                    ++nlength[len];

            len = 0;
            state = IN;
        }
    }
    for (int i = 0; i <= MAX; ++i) {
        printf("%d ", i);
        for (int a = 0; a < nlength[i]; ++a)
            printf("*");

        printf("\n");
        }
    return 0;
}



OUTPUT:
./histogram < histogram.c
0 
1 *************************************
2 *************************
3 **************
4 ************
5 *****
6 ******
7 ****
8 **
9 *
10 ***

Solution

  • First you need to know the height of the histogram which is the maximum value. Then you print each row and you decide to put a * or a according to the value.

    int h_max = 0;
    for (int a = 0; a < MAX; a++) {
      if (h_max <= nlength[a]) h_max = nlength[a];
    }
    
    for (int i = h_max; i >= 0; i--) {
        for (int a = 0; a < MAX; ++a) {
          if (nlength[a] > i) {
            printf("*"); 
          } else {
            printf(" ");
          }
        }
        printf("\n");
    }
    

    Another solution is to print horizontally into an array and print the array in the direction you want.