Pascal - Case Statement

Contents[Hide]

You have observed that if-then-else statements enable us to implement multiple decisions in a program. This can also be achieved using the case statement in simpler way.

 

1. Syntax:

The syntax of the case statement is:

case(expression) of
   L1 : S1;
   L2: S2;
   ...
   ...
   Ln:Sn;
end;
 

Where, L1, L2... are case labels, or input values which could be integers, characters, boolean or enumerated data items. S1, S2, ... are Pascal statements, each of these statements may have one or more than one case label associated with it. The expression is called the case selector or the case index. The case index may assume values that correspond to the case labels.

The case statement must always have an end statement associated with it.

The following rules apply to a case statement:

 

2. Flow Diagram:

case statement

 

3. Example:

The following example illustrates the concept:

program checkCase;
var
   grade:char;
begin
   grade :='A';
   case(grade) of
      'A': writeln('Excellent!');
      'B','C': writeln('Well done');
      'D': writeln('You passed');
      'F': writeln('Better try again');
   end;     
   writeln('Your grade is  ', grade );
end.
 

When the above code is compiled and executed, it produces following result:

Excellent!
Your grade is A