Case Statements

A case statement allows selection of one of multiple groups of statements to be executed. When there are several possibilities to choose from, it makes a neater solution than the use of multiple if statements.

program Integers2;
{$APPTYPE CONSOLE}
var
  Num1, Num2, Sum, Difference, Product, Choice : integer;
begin
  write('Please enter a whole number between 1 and 100 ');
  readln(Num1);
  write('Please enter another whole number between 1 and 100 ');
  readln(Num2);
  writeln('Would you like to know ..');
  writeln('the sum?  Enter 1');
  writeln('the difference?  Enter 2');
  writeln('the product?  Enter 3');
  readln(Choice);
  case Choice of
    1: begin
         Sum := Num1 + Num2;
         writeln(Num1 , ' + ', Num2, ' = ', Sum);
       end;
    2: begin
         Difference := Num1 - Num2;
         writeln(Num1 , ' - ', Num2, ' = ', Difference);
       end;
    3: begin  
         Product := Num1 * Num2;
         writeln(Num1 , ' * ', Num2, ' = ', Product);
       end;
  end;
  readln;
end.

Program Functions makes good use of a case statement by calling procedures from its menu. (Some of you may need to study procedures first in order to understand it, while others will learn from it how to write and use a procedure).

The next example shows the use in a case statement of:

  • else;
  • a list of selectors separated by commas;
  • a range (7..8).
program CaseDemo;
{$Apptype Console}
var
  MonthNum : integer;
begin
  write('Please enter a month number from 1 to 12. ');
  readln(MonthNum);
  case MonthNum of
    2: writeln('February usually has 28 days but has 29 in a leap year.');
    4, 6, 9, 11: writeln('Month ', MonthNum, ' has 30 days.');
    1, 3, 5, 7..8, 10, 12: writeln('Month ', MonthNum, ' has 31 days.');
   else
     writeln('Your number was not in the requested range.');
   end;
  readln;
end.    
Features introduced:
  • The case statement
  • The use of else, lists and ranges in case statements
  • Selecting from a menu of choices
Programming - a skill for life!

How to use if and case statements