Logo  

CS256 - Fundamentals of Structured Programming

Displaying exercises/e7/solution/p5.c

#include <stdio.h>

/**
 * Make a program that reads characters from the stdin (using getchar() and only
 * getchar()) and keeps track of how many of each letter (a-z) it reads.
 * Uppercase letters should be counted the same as a lowercase letter (i.e. 'a'
 * and 'A' are both counted as an 'a'.) After all the characters have been read,
 * print out a listing of the counts for each letter in the form of
 * "letter : count".  You may not use any standard library functions other than
 * getchar() for this assignment, i.e. no ctype functions.
 * 
 * Example input/output:
 * ./p5 < Makefile
 * a : 13
 * b : 9
 * c : 17
 * d : 9
 * e : 9
 * f : 14
 * ...
 * 
 * Hint: To do this problem correctly, you need an array that is 26 integers
 * in size.  Initialize the arrays elements to all zero before entering the
 * input loop.  For each character read, if it's a letter add one to that
 * characters array index ('a' (and 'A') should be index 0, 'b' index 1, and so
 * on.). After the loop, print out the values in the array with the character
 * it represents.
 * Hint 2: 'a' + i where 0 <= i <= 25 will give you the letters 'a'-'z'.
 */

int main(void)
{
  int letters[26];
  int c;
  
  for(c = 0; c < 26; c++)
    letters[c] = 0;

  while ((c = getchar()) != EOF) {
    if (c >= 'a' && c <= 'z') letters[c-'a']++;
    if (c >= 'A' && c <= 'Z') letters[c-'A']++;
  }

  for(c = 0; c < 26; c++) {
    printf("%c : %d\n", c+'a', letters[c]);
  }
  return 0;
}