Vertical histogram in C language

72 views Asked by At

I am able to print a histogram with a horizontal orientation with no problem. The exercise in my book also says to print one vertically. I have gotten the histogram to print, however the spacing for the *'s are off. I have attached a screenshot of the program. It is supposed to count the number of letters in a word, assign that number to an array with x value, then print a histogram, with the number of letters in a word then the array[wordlength]. In this case wordlength1 would be 1 and get 1 star, then wordlength2 = 2 so there should be two stars. It prints the two stars, just not in the correct spot.

Sample Run

Below is my code:

#include <stdio.h>

#define IN 1            /* In a word */
#define OUT 0           /* Out of word */
#define MAXWORDLENGTH 10    /* Maximum word length */

main() {

    int c = 0, i = 0, j = 0, state = 0, letters = 0;
    int numstars = 0;               /* Length of graph */
    int ovflow = 0;                 /* Variable to catch words too long */
    int worldlengths[MAXWORDLENGTH];        /* Define array wordlengths */

    for (i = 1; i <= MAXWORDLENGTH; i++) {          /* Array to set  worldlengths to 0 */
        worldlengths[i] = 0;
    }

    while ((c = getchar()) != EOF) {
        if (c == ' ' || c == '\t' || c == '\n') {
        state = OUT;            /* Out of word */
            if (letters > 0) {
                if (letters <= MAXWORDLENGTH) {
                    worldlengths[letters]++; /* Add 1 to the array value for letters length */
                } else {
                    ovflow++;
                }
            letters = 0;        /* Start counting new word */
            }                                               
        } else if (c == 'q') {
            break;
        } else if (state = OUT) {
            state = IN;                 /* In a word */
        letters += 1;                   /* Start of word */
        } else {
            letters++;                  /* Counting word length */
        }
    }

    for (i = MAXWORDLENGTH; i >= 1; i--) {
        for (j = MAXWORDLENGTH; j >= 1; j--)
        numstars = worldlengths[i];
        while (numstars > 0) {
            printf("  1\n");
            numstars -= 1;
        }
        if  (numstars == 0) {
//          printf("   ");
        }
    }

    for (i = 1; i <= MAXWORDLENGTH; i++) {
        printf("%3d", i);
    }

    putchar('\n');

    for (i = 1; i <= MAXWORDLENGTH; i++) {
        printf("%3d", worldlengths[i]);
    }

}

any suggestions? I am attempting to learn C programming on my own and would greatly appreciate any help.

0

There are 0 answers