L-18 MCS 260 Mon 1 Oct 2001

Below are the complete versions of the programs we discussed in class. We have seen how to calculate with charaters and how to use some of the functions in ctype.h.
/* L-18 MCS 260 Mon 1 Oct 2001 : convert letter grades into values 

With every letter grade corresponds a numerical value as follows :

     letter |  numerical
     grade  |    value
   ---------+------------
       a    |     10
       b    |      9 
       c    |      8 
       d    |      7 
       e    |      6 
       f    |      5 

In the program below we show how to use "character arithmetic",
that is arithmethic with ASCII codes, to translate letter grades
in their corresponding numerical values.  */

#include <stdio.h>

int main(void)
{
   char grade;
   int value;

   printf("Give a grade : ");
   grade = getchar();

   if ((grade < 'a') || (grade > 'f'))
      printf("  Invalid grade.\n"
             "  Please enter letter between \"a\" and \"f\".\n");
   else
   {
      value = 10 + ('a' - grade);
      printf("The grade \"%c\" corresponds to %d.\n", grade, value);
   }

   return 0;
}
  
In the program below we apply some of the functions in ctype.h. Of great importance is the usage of previous_ch to remember the previous character read.
/* L-18 MCS 260 Fri 28 Sep 2001 : formatting of names

The first letter of a name (first and last) are usually written
in capital letters, while other characters are lower case.
The program below put any sequence of characters in this format,
using the functions in c.type.h. 

To use this program, redirect the input, i.e.: a.out < names,
where the file "names" can contain the following

   brIAn w. KERNIGAN
   dEnnis m. RITCHIE

After typing a.out < names at the command prompt, 
you should then see

   Brian W. Kernigan
   Dennis M. Ritchie

The code below is written with putchar and getchar, it is a
good exercise to convert everything with scanf and printf.  */

#include <stdio.h>
#include <ctype.h>

int main(void)
{
   int previous_ch = ' ';
   int ch;

   while ((ch = getchar()) != EOF)
   {
      if isspace(previous_ch)
         putchar(toupper(ch));
      else
         putchar(tolower(ch));

      previous_ch = ch;
   }

   return 0;
}