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

PROGRAM CASE1;
USES dos, windos;
VAR y,m,d,dw: word;
VAR day: string[10];
BEGIN
   getdate(y,m,d,dw);
   CASE dw of
      0: day:='Sunday';
      1: day:='Monday';
      2: day:='Tuesday';
      3: day:='Wednesday';
      4: day:='Thursday';
      5: day:='Friday';
      6: day:='Saturday';
   END;

   writeln('Today is ',day);
   readln;
END.

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

PROGRAM case2;
USES crt;
VAR lottno: integer;
BEGIN
   clrscr;
   randomize;
   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);
   END;

   writeln('The lucky number is ', lottno);
   readln;
END.

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

PROGRAM case3;
USES crt;
VAR age, fee: integer;
BEGIN
   clrscr;
   write('Enter your age last birthday ');
   readln(age);
   CASE age of
      5..17 : fee:=50;
      18..24 : fee:=100;
      ELSE fee:=150;
   END;

   writeln('Your annual subscription is £', fee);
   readln;
END.

The ELSE statement includes all other values not previously listed within the case statement.

Exercises

  1. Adapt the first example program to report the full date in words (eg Monday 25th of September).
  2. 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

  3. 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.