|
~ Introduction to Programming: C ~ Session 8 - Character Variables |
In This Session...
In this session we will be covering the following topics:-
Last session we covered:-
We have looked at two types of variables so far - integers and floating-point or real variables. These are defined as follows:-
int i; float f;
where the first example creates a new variable called i which can hold whole numbers (e.g. -1, 0, 1, 2 etc.), and the second creates a new variable called f which can hold fractional numbers (e.g. 1.5, 2.345, -1.5, 7.0 etc.)
Character variables can hold a single symbol - typically something you could type in by pressing a key on the keyboard. This can include any letter, a single digit, and various symbols (e.g. !"£$%^&*()_ etc.) Declare a new character variable like this:-
char ch; char ch1,ch2,ch3;
The first example declares a new variables called ch which can hold a single character. The second example declares three new variables, all of which can hold a single character, called ch1, ch2, and ch3.
To place a value into a variable:-
ch='a'; ch1='1'; ch2=ch1; ch3=ch1+1; ch=ch+2;
Notice that we use single quotes to surround the character to be placed into the variable. The examples can be read as follows:-
variable ch becomes 'a' or put the letter a into the variable called ch
variable ch becomes '1' - note that this is just the symbol '1' rather than the number 1.
variable ch2 gets a copy of the contents of variable ch1 - i.e. it now contains '1' too.
variable ch3 gets a copy of the contents of variable ch1, but 1 is added to it. This means that the next symbol on from the digit '1' will be used - i.e. '2'.
variable ch gets a copy of itself, but 2 is added to it. As ch originally contained 'a', the next symbol on is 'b' and the next symbol after that is 'c' (i.e. plus 2 means 2 symbols on), so the variable ch now contains the letter 'c'.
The idea that we can treat a character as a number, and add a number to it to get a different symbol is an unusual ability in a computer language. It can be very useful in some applications, but don't get carried away with using it unnecessarily!
If we wish to wait for a key to be pressed at the keyboard, we are used to using getch(); - what we may not have known was that this function actually returns (i.e. gives) a value - i.e. the key pressed on the keyboard. To get hold of that key pressed, we do this:-
ch=getch();
Now the variable ch contains whatever was pressed on the keyboard. Similarly:-
ch=getche();
does the same thing, except the key pressed is shown (echoed) onto the console window.
We can display a character in the printf statement as follows:-
printf("You pressed the letter %c\n",ch);
So just as %d is used to display integer variable, and %f is used to display real or floating-point variables, %c is used to display character variables.
Just say we wanted to give three options - 'A', 'B' and 'C'. We could use our do...while loop with getche() to do this:-
do {
printf("Which option? A/B/C? "); ch=getche(); printf("\n");
} while ((ch<'A')||(ch>='C'))
The only problem here is - what happens if the person does not type in a capital letter, but rather small letters? These are treated differently, so the loop would not end.
What we can do is use another in-built function to convert the result of getche() first to be upper case, and then store the letter as upper case into the ch variable:-
#include <ctype.h>
...
do {
printf("Which option? A/B/C? "); ch=toupper(getche()); printf("\n");
} while ((ch<'A')||(ch>='C'))
Notice that the toupper function is held in the ctype library, so this needs to be included at the top of the program.
You may wonder what would happen if we pressed a digit or a symbols such as # or *. These (as well as letters that are already capitals) are left untouched by the toupper function.
Exercise 27 - What letter of the alphabet am I?
Remember that we can add numbers to characters to get the next character in sequence - e.g. adding 1 to 'a' gets us 'b'?
Well, we are going to utilise this idea to write a program that shows which letter of the alphabet is being input:-
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
main()
{
int ch;
printf("Which letter (a-z): "); ch=toupper(getche());
printf("\nThe letter number for %c is %d. Press a key.", ch, ch-'A'+1);
getch();
}
What happens here is that the letter gets converted to upper case and stored into the variable ch.
This is then displayed in a printf statement using the %c format modifier, and to get the number in the alphabet, the value of 'a' is subtracted from ch and 1 is added to this.
Let us take the example of 'A' begin chosen. If the value of 'A' is subtracted from this, we are left with 0 (there is no difference in sequence between the letters). Then 1 is added to this, giving a result of 1. In the case of 'B', the value of 'A' is subtracted from 'B', giving a difference of 1 between the letters. Add 1 to this to give the position of character 'B'.
The way this really works is that every symbol that you use is given a special number which C uses to work all this out. For example, a space has a code of 32, the digit '0' has a code of 49, the letter 'a' has a code of 97, and the letter 'A' a code of 65. Thus 'B' has a code of 66, and the '1' code is 50. These numeric equivalents are used to store the letters in a standardised way, and also transmit the letters similarly. The numbers are a standard defined by the American Standards Institute - otherwise known as the ASCII codes.
Exercise 28 - Validating our letters
Take the above example, and put a loop around the first printf and assignment to the ch variable. This loop should be a do...while loop with a condition that ensures that the value of ch must be between A and Z.
Exercise 29 - Yes/No Option to exit a program
We can use a loop to decide whether the user wishes to quit a program. Change the above program as follows:-
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
main()
{
int ch;
do
{
/* get a letter until a letter between a and y is pressed */
do
{
printf("\nWhich letter (a-z): "); ch=toupper(getche());
}
while ((ch<'A') || (ch>'Z'));
printf("\nThe letter number for %c is %d.", ch, ch-'A'+1);
/* Ask if another go is required until Y or N is pressed */
do
{
printf("\nAnother go (Y/N)? "); ch=toupper(getche());
}
while ((ch!='Y') && (ch!='N'));
}
while (ch=='Y'); /* loop if 'Y' was pressed */
printf("\nPress a key."); getch();
} /* end of main() */
Run the program and try it out. Notice we have two loops, each of which validate (check) one of a choice of correct letters is pressed. Both of these loops are within a bigger loop, which does everything over and over while the 'Y' option was chosen to have another go. This is a very common method for programs that give the option to exit the program - i.e. just about every program that is to be useful!
Notice that comments have been added to make explain what is going on in the program. This is a good idea in your own programs, so you can remember what different parts of the program do - it also helps others to understand your program's purpose - including examiners!
Typical output for this might be:-
Which letter (a-z): 5 Which letter (a-z): ! Which letter (a-z): Z The letter number for Z is 26. Another go (Y/N)? y Which letter (a-z): a The letter number for A is 1. Another go (Y/N)? y Which letter (a-z): J The letter number for J is 10. Another go (Y/N)? y Which letter (a-z): j The letter number for J is 10. Another go (Y/N)? l Another go (Y/N)? 0 Another go (Y/N)? 5 Another go (Y/N)? N Press a key._
Exercise 30 - Ten Green Bottles
Try the program below. It is an example of using loops to simulate a task you might do in real life - sing along, if you like!!!
#include <stdio.h>
#include <conio.h>
main()
{
int bottles = 10;
char plural;
printf("There were %d green bottles hanging on the wall", bottles);
do
{
getch(); clrscr();
if (bottles!=1) plural='s'; else plural=' ';
printf("%d green bottle%c hanging on the wall", bottles, plural);
getch(); clrscr();
if (bottles!=1)
printf("and if one green bottle should accidentally fall (tinkle!)...");
else
printf("and if that green bottle should accidentally fall (lonely tinkle!)...");
getch(); clrscr();
bottles--;
if (bottles!=1) plural='s'; else plural=' ';
printf("there\'ll be %d green bottle%c hanging on the wall", bottles, plural);
}
while (bottles > 0);
}
Notice the way that a character variable plural is used to show whether the bottle is plural or not, to put an 's' after bottles or no 's' after a single bottle. Run the program to see what happens.
Note also the use of another new function called clrscr(); which is short for clearscreen - it clears the screen of all writing and places the cursor at the top-left hand corner of the screen again. The clrscr() function is located in the conio library (same as the getch() function).
Change the program to start at 5 bottles instead. Easy?
Exercise 31 - Twelve Days of Christmas
Try the program below. It is an example of using loops to simulate a task you might do in real life - sing along, if you like!!!
Okay, try writing a program that does a similar sort of job, but for the twelve days of Christmas. You will need to use a load of if statements that looks something like this (inside a loop):-
if (day=12) then printf("twelve drummers drumming\n");
if (day>=11) then printf("eleven pipers piping");
if (day>=10) then printf("ten lords a leaping");
...etc. etc.
The carol starts each verse with:-
"On the nth day of Christmas my true love sent to me..."
The nth bit is trickier than you may think - e.g. 1st, 2nd, 3rd, 4th - see what I mean? The endings are different for different numbers.
and then the list of presents (first verse has first day, with one present, second verse has second day, with two presents etc.)
The twelfth day would look like this:-
|
On the 12th day of Christmas |
If you would like to see all of the verses (and if you have a sound card, hear the accompanying tune) click here to visit the twelve days web site.
Entry forms will be given out during the session. If you wish to enter any of the exams, you will need to complete this by Session 13 (18th December 2002) - Hand the form in at reception after completing it, and getting it signed by the person taking the class (me!). If you wish to pay by cheque, please make this payable to Northampton College.
Click here to see a full-colour sample of how to fill in the form, or click here for a black-and-white version.
For more information about the exam module structure, see session 6 notes.
Solutions to Exercise 31 - Twelve Days of Christmas
Using the if statement, the following would be a perfectly acceptable solution:-
#include <stdio.h>
#include <conio.h>
main()
{
int day_number;
for (day_number=1; day_number<=12; day_number++)
{
printf("On the %d",day_number);
if(day_number==1) printf("st");
else if (day_number==2) printf("nd");
else if (day_number==3) printf("rd");
else printf("th");
printf(" day of Christmas\n");
printf("my true love sent to me:\n\n");
if (day_number==12) printf("Twelve drummers drumming\n");
if (day_number>=11) printf("Eleven Pipers Piping\n");
if (day_number>=10) printf("Ten Lords a Leaping\n");
if (day_number>= 9) printf("Nine Ladies Dancing\n");
if (day_number>= 8) printf("Eight Maids a Milking\n");
if (day_number>= 7) printf("Seven Swans a Swimming\n");
if (day_number>= 6) printf("Six Geese a Laying\n");
if (day_number>= 5) printf("Five Golden Rings\n");
if (day_number>= 4) printf("Four Calling Birds\n");
if (day_number>= 3) printf("Three French Hens\n");
if (day_number>= 2) printf("Two Turtle Doves\n");
if (day_number>1) printf("and ");
if (day_number>= 1) printf("a Partridge in a Pear Tree\n");
getch(); clrscr();
}
}
However, once we have learned about the switch...case statement, the following would be a better solution:-
#include <stdio.h>
#include <conio.h>
main()
{
int day_number;
for (day_number=1; day_number<=12; day_number++)
{
printf("On the %d",day_number);
switch(day_number) {
case(1): printf("st"); break;
case(2): printf("nd"); break;
case(3): printf("rd"); break;
default: printf("th");
}
printf(" day of Christmas\n");
printf("my true love sent to me:\n\n");
switch(day_number) {
case(12): printf("Twelve drummers drumming\n");
case(11): printf("Eleven Pipers Piping\n");
case(10): printf("Ten Lords a Leaping\n");
case( 9): printf("Nine Ladies Dancing\n");
case( 8): printf("Eight Maids a Milking\n");
case( 7): printf("Seven Swans a Swimming\n");
case( 6): printf("Six Geese a Laying\n");
case( 5): printf("Five Golden Rings\n");
case( 4): printf("Four Calling Birds\n");
case( 3): printf("Three French Hens\n");
case( 2): printf("Two Turtle Doves\nand ");
case( 1): printf("a Partridge in a Pear Tree\n");
}
getch(); clrscr();
}
}
In the next session we will be covering the following topics:-
Using Break; and Continue;
Selecting distinct options using switch statement
Defining constants using #define
Accumulating totals using += operator
Exam entry forms given out and exam procedure explained.
![]()
(c) Copyright
2002-4 Simon Huggins. All Rights Reserved.
If you have any issues or questions regarding the content of this web
site, please contact the
author by clicking here.
Alternatively, you can leave a voice message on 00 44 (0)7050-618-297 or fax
on 00 44 (0)7050-618-298
This Page was last updated: 29 January 2004 13:06