K&R C Exercise 1-14: Histogram of the frequency of types of characters This is for K&amp;R C Exercise 1-14: basically asking to create a program that prints a histogram of the frequency of types of characters. This is done with very basic C functions/knowledge as covered in the first chapter.

I feel like this code as it stands is pretty clunky with all the for loops to print (though it does function!) Is there a simple way to reduce the number of loops (and also the loop variables) in a more concise way?

#include &lt;stdio.h&gt;

int main()
{
    int c, i, j, k, l, h, nwhite, nother;
    int ndigits[10];

    nwhite = nother = 0;

    for (i = 0; i &lt; 10; ++i)
        ndigits[i] = 0;

    while ((c = getchar()) != EOF)
    {
        if (c &gt;= '0' &amp;&amp; c &lt;= '9')
            ++ndigits[c-'0'];
        else if (c == '\n' || c == '\t' || c == ' ')
            ++nwhite;
        else 
            ++nother;
    }
    for (j = 0; j &lt;= nwhite; ++j)
    {
        if (nwhite - j &gt; 0)
            putchar('*');
    }
    putchar('\n');
    for (k = 0; k &lt;= nother; ++k)
    {
        if (nother - k &gt; 0)
            putchar('*');
    }
    putchar('\n');
    for (i = 0; i &lt; 10; ++i)
    {
        for (h = 0; h &lt; ndigits[i]; ++h)
        {
            if (ndigits[i] - h &gt; 0)
                putchar('*');
        }
        putchar('\n');
    }
}
Nice job on your code. I only have a few things to say along with some extra nit-picks at the end.



Refactor

I see this construct a lot in your code:


for (j = 0; j &lt;= nwhite; ++j)
{
    if (nwhite - j &gt; 0)
        putchar('*');
}
putchar("\n");



Of course, different variables are used every time, but the concept is the same. You could actually simplify your code if you extracted this logic to a separate function. Here is what I mean:

void print_stars(limit) {
    for(int i = 0; i &lt; limit; i++) {
        if(limit - i &gt; 0) {
            putchar("*");
        }
    }
    putchar("\n");
}


Now, you can just use this function every time you come across this construct:

print_stars(nwhite);
print_stars(nother);
for (i = 0; i &lt; 10; ++i)
{
    print_stars(ndigits[i]);
}




Nitpicks

That refactoring was really all I had to say about your code. These are just extra (yet important) things.


Always use braces. I notice that you've omitted braces on some if statements, and that's probably because K&amp;R does that a lot. In actual code, this is bad practice because it can lead to hard-to-find yet easy-to-get bugs.
You can simplify initializing arrays with 0s with this:

int ndigits[10] = {0};



There is no need for an extra loop to do this.