LESSON 2

 

SELECTION Construct

 

We make decisions everyday. The decisions we make may include the way we dress, the food we eat, when we eat, which bus to take when going somewhere and so on.

In order to make the computer make 'decisions', we have to give it instructions to do so. In the Pascal programming language this is done by using the IF..THEN..ELSE or the CASE..OF.. statements.

When a program section encounters this decision making process it is known as selection.

The IF..THEN..ELSE statements is similar to the way we make our decisions. For example:

 

IF hungry THEN

eat;

or

 

IF tired THEN

rest;

 

Or we may even make decisions based on multiple conditions like:

 

IF hungry AND food available THEN

find a place to sit and eat all you want.

 

hungry and food available are known as conditions.

 

Conditions can have only two results :

TRUE or FALSE.

These are known as BOOLEAN values.

 

 

Compound Condition

 

When a conditional statement contains more than one condition, it is known as a compound condition.

 

 

No alternative

We sometimes make a choice because there are no alternatives left. In Pascal programming this can be illustrated by using the ELSE statement, as in real life:

 

IF hunger strikes THEN

eat some food

ELSE IF very tired THEN

get some rest

ELSE IF homework not done THEN

complete the homework

ELSE

read the newspaper.

 

 

 

Relational

Operator Meaning

>

Greater than

<

Lesser than

>=

Greater or equals to

<=

Lesser or equals to

=

Equals to

<>

Not equals to

 

Logical

Operators Meaning

AND

Logical conjugation

OR

Logical disjunction

NOT

Logical negation

 

 

Analyze the following programs ...

 

Program 2-1

 

program SpeedingVehicle;

uses CRT;

var

Speed : real;

begin

ClrScr;

Write('Enter Vehicle Speed : ');

ReadLn( Speed );

if Speed > 110 then

WriteLn('Speeding !!')

else

WriteLn('Safe speed.');

ReadLn;

end.

 

 

This is a simple program which prints out "Speeding !!" if the speed input is greater than 110 or else it will print "Safe speed.". Check out the other program.

Program 2-2

program BiggerOfTwo;

uses CRT;

var

First, Second : integer;

begin

ClrScr;

Write('Enter a number: ');

ReadLn( First );

Write('Enter second number : ');

ReadLn( Second );

 

if A > B then

WriteLn(‘Bigger number is : ‘, A)

else

WriteLn(‘Bigger number is : ‘, B);

ReadLn;

end.

 

Program 2-3

program BoyOrGirl;

uses CRT;

var

Sex : Char;

begin

ClrScr;

Write(‘Are you a (M)ale or (F)emale :’);

ReadLn( Sex );

If Sex = ‘M’ Then

WriteLn(‘You are a guy’)

else

WriteLn(‘You are a gal’);

end.

 

There is a limitation in the above program. Only a capital ‘M’ will result in ‘You are a guy’ to be displayed. Any other key will result in ‘You are a gal ‘ to be displayed.

The lowercase ‘m’ will result in ‘You are a gal’ to be shown.

 

To improve the previous program (to accecpt ‘m’ or ‘M’ for a "guy".

Program 2-4

program BoyOrGirl2;
uses
CRT;

var

Sex : Char;

begin

ClrScr;

Write(‘Are you a (M)ale or (F)emale :’);

ReadLn( Sex );

If (Sex = ‘M’) or (Sex=‘m’) Then

WriteLn(‘You are a guy’)

else

WriteLn(‘You are a gal’);

end.

 

Program 2-5

program BoyOrGirl3;
uses
CRT;

var

Sex : Char;

begin

ClrScr;

Write(‘Are you a (M)ale or (F)emale :’);

ReadLn( Sex );

If (Sex = ‘M’) or (Sex=‘m’) Then

WriteLn(‘You are a guy’)

else

WriteLn(‘You are a gal’);

end.

 

This segment shows the use of the IN operator.

Program 2-3

program TestIfThen;

uses CRT;

var

Score : integer;

Grade : string;

begin

ClrScr;

Write('Please Enter Score : ');

ReadLn( Score );

if Score >= 90 then

Grade := 'Distinction'

else if Score >= 70 then

Grade := 'Credit'

else if Score >= 50 then

Grade := 'Pass'

else

Grade := 'Fail';

WriteLn('Student''s Grade : ', Grade );

ReadLn;

end.

 

Here, a score is input by the user and it is checked against several values and a proper grade is assigned to the variable GRADE. If the score is greater or equals to 90 then the grade is DISTINCTION, or else if the score is greater or equals to 70 then the grade is CREDIT and so on. After that the grade is output by the program.

 

IN relational operator and SUBRANGES.

 

There is another relational operator which is used to compare values within a set. It is the IN operator. Consider this program

Program 2-3

program CharacterSets;

uses CRT;

var

Ch : char;

begin

ClrScr;

Write('Type a character : ');

ReadLn( Ch );

if Ch in ['A'..'Z'] then

WriteLn('A capital letter was typed')

else if Ch in ['a'..'z'] then

WriteLn('A small letter was typed')

else if Ch in ['0'..'9'] then

WriteLn('A digit was typed')

else

WriteLn('Something was typed !');

ReadLn;

end.

 

This segment shows the use of the IN operator. It is much simpler to write and clearer to read, but you must remember that the IN operator only works on sets and ordinal types.

 

Here is a program showing the use of the logical operators in a validation routine:

Program 2-4

program ValidateScore;

uses CRT;

var

Score : real;

begin

ClrScr;

Write('Enter a test score : ');

ReadLn( Score );

if (Score > 100) or (Score < 0) then

begin

TextColor( LightRed + Blink );

WriteLn('Error!! Invalid Score...');

WriteLn('Scores must be between 0 and 100.');

end;

ReadLn;

end.

 

A score is entered by the user and checked whether it exceeds the maximum or minimum amount. If it exceeds either one, then an error message in blinking red is shown.

 

Notice that we NEED parentheses if there are more than 2 conditions to be tested. The BEGIN..END block is also needed because there are more than one statement to be executed if the condition is true. In previous examples the BEGIN..END block was not necessary because there was only one statement being executed if the condition was true.

 

Compound Condition

An if statement may contain more than one condition.

In this case, these conditions are known as compound statements. Compound statements can be created by using the reserved words AND or OR.

 

AND

TRUE

FALSE

TRUE

TRUE

FALSE

FALSE

FALSE

FALSE

eg:

 

if ( Score <= 100 ) and ( Score >= 0 ) then

WriteLn('Valid Score');

 

Note:

 

'Valid Score' will only be printed if the score is between 0 AND 100. See, it resembles English.

 

OR

TRUE

FALSE

TRUE

TRUE

TRUE

FALSE

TRUE

FALSE

eg:

 

if ( A > B ) or ( C < D ) then

WriteLn('Values are out of order.');

 

Note :

'Values are out of order' is printed if either conditions ( A > B OR C < D ) is true. If neither conditions are true, then the statements are not executed.

 

The NOT operator negates the result of a condition. NOT changes TRUE to FALSE and FALSE to TRUE. Think of it this way...

What is NOT TRUE? FALSE

What is NOT FALSE? TRUE

What is NOT dark? Bright

What is NOT Black? White

What is NOT Funny? Dunno!

 

This will be elaborated in later lessons when using the operator becomes more relevant.

 

CASE..OF

 

The next conditional statement available to Pascal programs is the CASE..OF statement.

This is the syntax of the CASE..OF statement:

 

CASE selector OF

label_list_1 : statements_1;

label_list_2 : statements_2;

label_list_3 : statements_3;

.... ....

.... ....

label_list_n : statement_n;

ELSE

statement_else;

END;

 

The SELECTOR must be an ordinal type. The SELECTOR can also be an ordinal expression. Therefore the LABEL-LISTS involved can only contain ordinal values. There may be more than one value in a LABEL-LIST. The statements can be compound, conditional, iterative etc. but you must place a BEGIN..END block if the statement is compound.

Program 2-5

program TestCaseOf;

uses CRT;

var

Num : integer;

begin { main program }

ClrScr;

Write('Type in a number between 1 and 5 : ');

ReadLn( Num );

Write('You typed ');

case Num of

1 : WriteLn('One');

2 : WriteLn('Two');

3 : WriteLn('Three');

4 : WriteLn('Four');

5 : WriteLn('Five');

else

WriteLn('a number out of range.');

end; { case }

ReadLn;

end. { main program }

 

In this program, the user has to input a value between 1 and 5. The value typed by the user is stored in the variable NUM which is of integer type. Then the CASE statement starts.

 

Here's how you can read the case statement:- in CASE the variable NUM has the value of 1, the first statement is executed. In CASE the variable NUM has the value of 2, the second statement is executed and so on. The comment is put at the end of the case statement to clarify the ending of the selections.

 

The statements here are simple statements, so the BEGIN..END block is not required.

 

Consider this code segment...

case Score div 10 of

10,9 : Grade := 'A';

8 : Grade := 'B';

7 : Grade := 'C';

6 : Grade := 'D';

0,1,2,3,4,5 : Grade := 'F';

end; {case}

 

In this code segment, multiple values are compared with the result of the score divided by 10. Also take note that there is more than one value in the label-list.

 

The case statement is very useful when implemented with a menu or when there are many choices to determine. But, you must remember that the SELECTOR type can only be an ordinal type.

 

Here is another program to try...

Program 2-6

program TrafficLights;

uses CRT;

var

Color : char;

begin

ClrScr;

WriteLn('[R]ed / [A]mber / [G]reen ');

Write('Which color : '); ReadLn( Color );

Color := upcase( Color );

case Color of

'R' : WriteLn('Stop your vehicle');

'A' : WriteLn('Prepare to stop');

'G' : WriteLn('Vehicle may GO');

else

WriteLn('You chose a wrong color');

end; { case }

ReadLn;

end.

 

Subranges can also be tested using the CASE statement

Program 2-6

program WhichTypeOfItem;

uses CRT;

var

Item : char;

begin { main program }

ClrScr;

Write('Enter An Item (CHAR) : ');

ReadLn( Item );

case Item of

'A'..'Z' : WriteLn('Capital letter was typed.');

'a'..'z' : WriteLn('Small letter was typed.');

'0'..'9' : WriteLn('Digit was typed.');

else

WriteLn('Don''t know what was typed.');

end; { case }

ReadLn;

end. { main program }

 

Selection statements are used when a certain block of code is to be executed based on certain conditions. If the conditions are false, the code should not be executed. Don't forget the two different ways with which Pascal can implement the selection construct.

 

The pseudocode for the IF..THEN statement may be written in this format:

 

IF condition-1 THEN

statements-1

ELSE IF condition-2 THEN

statements-2

ELSE

statements-else

ENDIF

 

The CASE..OF statement pseudocode may look like this:

 

CASE variable IS

value-1 :- statements

value-2 :- statements

value-3 :- statements

ELSE

statements

ENDCASE

 

 

1