Turbo Pascal 7.0 Guide
The Case Statement
The case statement is used to allow your program to perform different actions depending on the value of a variable. In the examples, the case statement is shown in bold.
Example 1 - Working Out The Day Of The Week
USES dos, windos;
VAR y,m,d,dw: word;
VAR day: string;
CASE dw of
writeln('Today is ',day);
In this program, the external libraries dos and windos are used. These two libraries are required to allow Pascal to read the date from the system clock.
The word variable type allows only positive integers to be stored.
Attempting to store a negative integer in such a variable would generate an error that a well-written program could prevent or handle.
The indentation is used to make the program more readable and is considered good practice in programming.
Example 2 - Colouring Numbers
VAR lottno: integer;
lottno:= trunc(random(49)) +1;
CASE lottno of
0..9 : textcolor(white);
10..19 : textcolor(cyan);
20..29 : textcolor(yellow);
30..39 : textcolor(green);
40..49 : textcolor(magenta);
writeln('The lucky number is ', lottno);
The crt library gives access to screen functions such as clearing the screen and text colour.
Notice that you can have more than one value for each option within the case statement.
Example 3 - Membership Fees
VAR age, fee: integer;
write('Enter your age last birthday ');
CASE age of
5..17 : fee:=50;
18..24 : fee:=100;
writeln('Your annual subscription is £', fee);
The ELSE statement includes all other values not previously listed within the case statement.
- Adapt the first example program to report the full date in words (eg Monday 25th of September).
- Write a program that allows the user to enter a Module 1 examination score as an integer in the range 0 - 65. Convert the score into a grade using the boundaries specified below,
A - 47, B - 42, C - 37, D - 33, E - 29
- Write a program which allows the user to input a number in the range 1 - 10. If the user has entered a number in the range, output the number in words to the screen. If they enter a number out of range, display an error message telling them off.