The Case Statement resembles the if statement. Think of it as a combination of several if statements. The syntax is as follows:
Case Statement
where the case labels have following format:
Case Label
The general form is:
case any-variable of |
label-1 : statement-1; |
label-2 : statement-2; |
: |
label-n : statement-3 |
end |
label-x can contain many or just 1 value of the same type as the any-variable.
Important notes:
If the value of the any-variable is not listed within the label-x's, then an error is raised and the execution of the program is terminated.
A specific value of the an-variable can only be present in one of the label-x lists.
any-variable must be of an ordinal data type.
A case constant list can also be a subrange type, that is a whole interval.
Lets see how the case statement works on an example:
program isitevenorodd(input,output); |
var |
i:integer; |
begin |
read(i); |
case i of |
2,4,6,8 : writeln('i is even); |
1,3,5,7,9" writeln('i is odd') |
end |