CSM217: C for Computer Scientists

Lecture 2: Exercise 4: Solution

#include <stdio.h>
#include <ctype.h> // we're going to use some type handling functions

main() {
 char c; // store the character just read in a char, more efficient than int
 int charCount[26];
 int x, max; // x is an array subscript, max will hold the biggest value in the 
             // array (see later)

 for (x = 0; x < 26; charCount[x++] = 0); // initialise array

 while ((c = getchar()) != EOF) {
  if (isalpha(c)) { // if the input is an alphabetic character, in ctype.h
   c = tolower(c); // convert it to lower case, in ctype.h
   charCount[c-'a']++;
  }
 }

 // ok, all the data's been read. We can print the histogram...

 // need to find the biggest value in the array cell.
   
 max = 0; // initialise max

 for (x = 0; x < 26; x++) {
    if (charCount[x] > max) {
      max = charCount[x];
    }
 } 
 
 for (; max > 0; max--) {
  //printf("%d ");
  for (x = 0; x < 26; x++) {
   if (charCount[x] >= max) {
    putchar('x');
   } else {
    putchar(' ');
   }
  }
  putchar('\n');
 }
 // print the letters of the alphabet along the bottom
 for (x=0; x<26; x++){
  putchar('a'+x);
 }
 putchar('\n');
}