Hello! I've been wanting to learn C a while now and finally decided to pick up Kernighan and Ritchie's ANSI C. One of the 'projects' is to create a numbered histogram, which I successfully did.
I just would like to know if this could be further optimized or any other pointers you all may have.
Thanks!
Code:
/* Histogram for counting input of numbers.
Troy Martin, Beef Erikson Studios 2018 */
#include <stdio.h>
int main()
{
/* forward declares */
int c, i, j;
int ndigit[10];
/* variable / array assignment */
int number = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
/* reads input and puts numbers into corresponding array index */
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
printf("\n\n");
/* finds highest number */
for (i = 0; i < 10; ++i)
if (ndigit[i] > number)
number = ndigit[i];
/* display histogram based on highest number */
for (i = 0; i < number; --number) {
for (j = 0; j < 10; ++j) {
if (ndigit[j] >= number)
printf(" *");
else
printf(" ");
}
printf("\n");
}
/* prints footer */
for (i = 0; i < 10; ++i)
printf("%4d", i);
printf("\n\n Histogram of times each number was used.\n\n");
}
Here it is running: