The CASE statement
The case statement allows you to rewrite code which uses a lot of if else statements, making the program logic much easier to read. Consider the following code portion written using if else statements,

	if operator = '*' then result := number1 * number2
	   else if operator = '/' then result := number1 / number2
	       else if operator = '+' then result := number1 + number2
	           else if operator = '-' then result := number1 - number2
	               else  invalid_operator = 1;

Rewriting this using case statements,
	case  operator  of
	      '*' : result:= number1 * number2;
	      '/' : result:= number1 / number2;
	      '+' : result:= number1 + number2;
	      '-' : result:= number1 - number2;
	otherwise    invalid_operator := 1
	end;


The value of operator is compared against each of the values specified. If a match occurs, then the program statement(s) associated with that match are executed.

If operator does not match, it is compared against the next value. The purpose of the otherwise clause ensures that appropiate action is taken when operator does not match against any of the specified cases.

You must compare the variable against a constant, how-ever, it is possible to group cases as shown below,

	case  user_request  of
	      'A' :
	      'a' :  call_addition_subprogram;
	      's' :
	      'S' :  call_subtraction_subprogram;
	end;

PROGRAM TWELVE
Convert the following program, using appropiate case statements.

	program  PROG_TWELVE (input, output);
	var      invalid_operator : boolean;
	         operator : char;
	         number1, number2, result : real;
	begin
	         invalid_operator := FALSE;
	         writeln('Enter two numbers and an operator in the format');
	         writeln(' number1 operator number2');
	         readln(number1); readln(operator); readln(number2);
	         if operator = '*' then result := number1 * number2
	         else if operator = '/' then result := number1 / number2
	         else if operator = '+' then result := number1 + number2
	         else if operator = '-' then result := number1 - number2
	         else invalid_operator := TRUE;

	         if invalid_operator then
	            writeln('Invalid operator')
	         else
        	    writeln(number1:4:2,' ', operator,' ', number2:4:2,' is '
	                    ,result:5:2)
	end.

Click here for answer
Copyright B Brown/P Henry/CIT, 1988-1997. All rights reserved.

1