Winter 2004 CS 31 Section 1 (Shinnerl)

Programming Assignment 2: Character Analysis

DUE: 10:00PM Wed. 1/21

Write a C++ program to accept and process a single character of input from the user at run-time as follows.

  1. The program displays the ASCII value of the character. The program need process only those characters with ASCII values in the range 0-127. Unprintable characters (ASCII value between 0 and 31) need not be echoed to the screen in any special format.
  2. If the character is alphabetical, the program states its numerical position in the alphabet as an ordinal with the correct suffix ("st," "nd," "rd," or "th").

Sample I/O

Each line in the following table corresponds to a different execution of the program.
Input Output
+ The ASCII value of '+' is 43.
a The ASCII value of 'a' is 97. 'a' is the 1st letter of the alphabet.
b The ASCII value of 'b' is 98. 'b' is the 2nd letter of the alphabet.
K The ASCII value of 'K' is 75. 'K' is the 11th letter of the alphabet.
W The ASCII value of 'W' is 87. 'W' is the 23rd letter of the alphabet.
U The ASCII value of 'U' is 85. 'U' is the 21st letter of the alphabet.

Hints.

Suppose your program uses character variable myChar.
  1. Explicit conversion from character to integer type can be done in three ways:
    int(myChar) // C++ style cast
    (int) myChar // C style cast
    static_cast<int>(myChar) // C++ compile-time cast
    However, usually implicit casting is sufficient. Whenever a character appears in an arithmetic expression, the compiler automatically replaces it by its ASCII value: the value of ('A'+1) is 66, same as int('B').
  2. If you are clever, you can reduce the number of branches in your program to 5. You do not need 27 branches! You should reduce the number of branches to between 5 and 10.
  3. You can write the code for this assignment without knowing or using any specific ASCII values yourself. Let the compiler do the work.
  4. Characters may be compared directly, e.g., the boolean expression (myChar >= 'A' && myChar <= 'Z') is true if and only if the value of myChar is an upper-case letter.

Homework 2 Home Page