The operator of variant “case”

The operator of variant “case”


Questions

 


Answers

1. What assignment of operator of variant “case” in program?

The variant’s operator is allowed for executing one of several operators, depending on the value of variable, that is specified between the words “case” and “of“.


2. What is the general view of “case” operator?

The general view of variant operator is following:

case ordinal_expression of
  1: statement1; // executed if ordinal_expression=1
  2, 3: statement2; // executed if ordinal_expression = 2 or
                    // ordinal_expression = 3
  else
    statement 3; // executed in all other cases
end;

Here, the variable ordinal_expression is called as selector. Selector is the ordinal type.

statement1, statement2, statement3 – one or several operators (is placed between “begin” and “end“).

The numbers 1, 2, 3 have labels. Labels are separated from operators by colons. Labels take the values, that can take the selector. When referring to the “case” operator is executed the operator, the label of which corresponds to the value of the selector. Labels can be set as ranges.

The operator of variant “case” can be realized and without the use of the block “else“. In this case, the general view of operator “case” is following:

case ordinal_expression of
  1: statement1; // is executed when ordinal_expression=1
  2, 3: statement2; // is executed when ordinal_expression = 2 or
                    // ordinal_expression = 3
end;

If the value ordinal_expression does not contain any of values which are indicated on labels (1, 2, 3) then is executed the operator, which follows immediately after the “case” operator.


3. What feature of using the  “else” block in the operator “case“?

The operator that is placed after “else”, is executed when there if the selector value does not meet any of these labels.


4. An example of using the “case” operator without of using “else” block.

Is specified the number n (n = 1..3) which is the number of function. By using the value n calculate following:

01_02_02_01_07_formula_eThe code snippet, which solves given task:

...

case n of
  1: y:=sin(x);
  2: y:=cos(x);
  3: y:=sin(x)/cos(x);
end;

...


5. An example of using “case” operator by using “else” block.

Write a code snippet, which for a given month number “n” determines the number of days in that month. The number of days is saved in the variable k.

...

case n of
  2: k:=28;
  4, 6, 9, 11: k:=30;
  else
    k:=31;
end;

...


6. An example of using the “case” operator, where labels are specified by the range of values.

The code snippet, where by the number of a day n = 1..7, is determined – is this day the day off (true) or no (false).

...

case num of
  1..5: f_day_off := false;
  6,7: f_day_off := true;
end;

...