HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

K&R C Exercise 1-14: Histogram of the frequency of types of characters

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thefrequencyexercisehistogramtypescharacters

Problem

This is for K&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 

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

    nwhite = nother = 0;

    for (i = 0; i = '0' && c  0)
            putchar('*');
    }
    putchar('\n');
    for (k = 0; k  0)
            putchar('*');
    }
    putchar('\n');
    for (i = 0; i  0)
                putchar('*');
        }
        putchar('\n');
    }
}

Solution

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  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  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 < 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&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.

Code Snippets

for (j = 0; j <= nwhite; ++j)
{
    if (nwhite - j > 0)
        putchar('*');
}
putchar("\n");
void print_stars(limit) {
    for(int i = 0; i < limit; i++) {
        if(limit - i > 0) {
            putchar("*");
        }
    }
    putchar("\n");
}
print_stars(nwhite);
print_stars(nother);
for (i = 0; i < 10; ++i)
{
    print_stars(ndigits[i]);
}
int ndigits[10] = {0};

Context

StackExchange Code Review Q#121582, answer score: 4

Revisions (0)

No revisions yet.