CHAPTER 4

CONTROL STRUCTURES AND LOOPING

In every day life we make a lot of selections. We make proper selections based on some conditions. For example: If it is raining, use an umbrella. If head aches, then take an aspirin. When programming, decisions are also based on certain conditions. These conditions are used in IF..THEN..ELSE statements. Suppose you wish to write a program to print out whether a person passed or failed a course based on the average score, you could write a program like this one:

PROGRAM 4-1

Program PassFail (input, output);

VAR

AverageScore : integer;

BEGIN

Write ('Please enter the average score (integer only) ?

');

Readln (AverageScore);

If AverageScore > 69

then writeln ('PASS')

else writeln ('FAIL');

end.

 

 

Program run:

C:\TP>

Please enter the average score (integer only) ? 90

PASS

Please enter the average score (integer only) ? 75

PASS

Please enter the average score (integer only) ? 59

FAIL

Type EXIT to return to Turbo Pascal...

 

This program can be demonstrated using a flow chart as follows:

 

 

begin

 

Prompt and

read average score

 

average

score >69

F T

write write

fail pass

 

stop

 

 

 

 

 

 

Let us re-write the above program to assign letter grades, A for average of 90 - 100, B for 80 - 89, etc. In this case we have to make a statement like: if grade is greater than or equal to 80 and less than 90 then grade is B. Change the program as follows:

 

 

PROGRAM 4-2

Program PassFail (input, output);

VAR

AverageScore : integer;

BEGIN

Write ('Please enter the average score (integer only) ?

');

Readln (AverageScore);

If (AverageScore >= 90) and (AverageScore <= 100)

then writeln ('GRADE = A')

else if (AverageScore >= 80) and (AverageScore <90)

then writeln ('GRADE = B')

else if (AverageScore >=70) and

(AverageScore <80) then writeln ('GRADE = C')

else if (AverageScore >= 60) and

(AverageScore <70) then

writeln ('GRADE = D')

else writeln('FAIL');

end.

 

Program run:

C:\TP>

Please enter the average score (integer only?) 92

GRADE = A

Please enter the average score (integer only?) 85

GRADE = B

Please enter the average score (integer only?) 75

GRADE = C

Please enter the average score (integer only?) 60

GRADE = D

Please enter the average score (integer only?) 59

FAIL

Type EXIT to return to Turbo Pascal...

 

 

 

EXPLANATION OF THE PROGRAM

Let us take a look at the statement

If AverageScore >= 90 and AverageScore <= 100

then writeln ('GRADE = A')

First of all please note that no semicolon is inserted after each line. This is because the statement actually continues with the else part. There are several criteria that have to be tested before the grade is printed. They are:

Is the grade above 90?

Is the grade equal to 90?

Is the grade less than 100?

Is the grade equal to 100?

These are evaluated using operators called Boolean Operators. Boolean operators are like + or - operators in mathematics. The Boolean Operators are OR, AND, NOT, and XOR. Suppose the average is 95. We may conclude:

Grade is above 90 -- true

Grade is equal to 90 -- false

Grade is less than 100 -- true

Grade is equal to 100 -- false

Let us assign Boolean operators to these (Please refer to Appendix 4A for additional information about Boolean operators):

true OR false = true

true OR false = true

Take these resulting true, true and apply Boolean operator AND:

true AND true = true

The final result is "true". If the (whole) statement is true then the program will write GRADE = A. More about Boolean operators is given in Appendix 4A.

When there are several alternatives, using if-then-else statements may become cumbersome. Look at the following example that deals with months:

PROGRAM 4-3

PROGRAM NestedIf (input, output);

var

month: integer;

begin

write('Please enter month (1..12): ');

readln(month);

if (month >= 1) and (month <=12) then

begin

if month = 1 then writeln('January');

if month = 2 then writeln('February');

if month = 3 then writeln('March');

if month = 4 then writeln('April');

if month = 5 then writeln('May');

if month = 6 then writeln('June');

if month = 7 then writeln('July');

if month = 8 then writeln('August');

if month = 9 then writeln('September');

if month = 10 then writeln('October');

if month = 11 then writeln('November');

if month = 12 then writeln('December');

end

else writeln('Month number is invalid!');

end.

{It would be more efficient add the else clauses to this program. However, this program is written this way to teach the concept of CASE}

Program run:

Please Enter month (1..12): 11

November

Please enter month (1..12): 4

April

This program can be re-written to eliminate repetitive if's by using the CASE statement. Here it is:

 

 

PROGRAM 4-4

PROGRAM CaseExample (input, output);

var

month : integer;

begin

write('Please Enter month (1..12): ');

readln(month);

Case month of

1: writeln ('January');

2: writeln ('February');

3: writeln ('March');

4: writeln ('April');

5: writeln ('May');

6: writeln ('June');

7: writeln ('July');

8: writeln ('August');

9: writeln ('September');

10: writeln ('October');

11: writeln ('November');

12: writeln ('December');

else writeln('Month out of range!');

end;

end.

Program run:

Please Enter month (1..12): 15

Month out of range!

Please Enter month (1..12): 11

November

Please enter month (1..12): 4

April

 

Numbers 1..12 here are called SELECTORS. The SELECTOR must be an ordinal type (may not be a real number). There are some other restrictions; you may not use longInt, string or word types. You can have more than one value for the selector as follows:

CASE Character of

'a','A','e','E','I','i','O','o','U','u' : write('Vowel');

else writeln ('Consonant');

end;

You can also have more than one Pascal statement for each option (compound statement) as in the following example:

CASE average of

90..100 : begin

writeln ('Grade : A');

writeln ('You did an exceptional job!');

writeln ('Keep up the Good work!')

end;

80..90 : writeln('Grade : B'); {so on..}

end;

Let us now revisit the program we wrote earlier to find grades. This time we will use the CASE structure. Consider PROGRAM 4-5; it is much easier to read and shorter than the previous program (PROGRAM 4-2).

PROGRAM 4-5

PROGRAM Grade (input,output);

VAR

AverageScore: integer;

begin

write ('Please enter the average score (integer only) ');

readln(AverageScore);

CASE AverageScore of

90..100 : writeln('GRADE = A');

80..89 : writeln('GRADE = B');

70..79 : writeln('GRADE = C');

60..69 : writeln('GRADE = D');

else writeln ('FAIL')

end;

end.

Let us leave CASE and talk more about Boolean variables. Variables of Boolean type may make a program more readable. Supposing that odd numbered houses (addresses) are on the south side of the street, consider the following statements:

A. If address mod 2 = 1 then writeln ('South side');

B. If address mod 2 = 1 then south := true;

If south then writeln('South side);

C. If not(south) then writeln('North Side');

Instructions A and B do the same thing. However, Instruction set B is more readable than A. Notice there is no need to say "if south = true then writeln.....)". Furthermore, notice the use of Boolean variable in instruction C.

Here is an example of a program that uses a Boolean type variable. This program can be used to determine if a house is located on the north side of the street or on the south side.

 

PROGRAM 4-6

Program BOOLEXAMPLE (input, output);

 

var

south : Boolean;

address : integer;

begin

south:=false;

write('PLEASE ENTER YOUR HOUSE NUMBER: '); {enter only integer}

readln(address);

if odd(address) then south:=true;

if south then

writeln('YOUR HOUSE IS ON THE SOUTH SIDE OF THE STREET')

else

writeln('YOUR HOUSE IS ON THE NORTH SIDE OF THE STREET');

end.

Program run:

PLEASE ENTER YOUR HOUSE NUMBER: 1635

YOUR HOUSE IS ON THE SOUTH SIDE OF THE STREET

PLEASE ENTER YOUR HOUSE NUMBER: 1634

YOUR HOUSE IS ON THE NORTH SIDE OF THE STREET

Please note that any variable that is not read within the program must be initialized. Notice that ADDRESS is read within the program, while SOUTH is not. Therefore, SOUTH was initialized (in this example, initialized as false). This example makes use of a function called ODD. Odd checks to see if the argument is an odd number and returns True or False.

EXPLANATION OF THE PROGRAM

The purpose of this program is to read an address and determine if the building is on the north side of the street or on the south side. At least in this city (where I live) all even numbered addresses are on the north side and all odd numbered on the south side.

This program uses two variables, ADDRESS is an integer and SOUTH is a Boolean. An integer variable can store values ranging from -32768 to +32787 while a Boolean variable can hold only two values, true or false. Pascal can read the value of an integer variable from the keyboard, while value of a Boolean variable cannot be read from the keyboard. Values of Boolean variable must be assigned within the program. Example: South := true; Y

You may not do this: Readln(South);

We initialize the variable South to false. The rest of the program should either change it to true or leave it alone (as false). At this point we read the address and determine if that address is odd or even. We could determine if a number is odd or even by using the MOD operator. If the result of ADDRESS MOD 2 is 0 then it is an even number; otherwise it is an odd number. However, in this program I chose to use a built in function called Odd, which does the same thing. Thus, if ADDRESS is odd then value of SOUTH will be changed to true. If ADDRESS is not odd, then the value of SOUTH will not change, i.e., it will remain false as we initialized it.

Next, we need to write the result out based on the value of the Boolean variable SOUTH. Notice how the statement is written:

If south then writeln('YOUR HOUSE IS ON THE SOUTH SIDE OF THE STREET'); There is no need to say If south = true then ...

You could also write this as: If not(South) then writeln('YOUR HOUSE IS ON THE NORTH SIDE OF THE STREET');

 

Appendix 4A

NOT, AND, OR, XOR are Boolean operators. These operators can be used to write Boolean expressions.

Examples:

not (10 > 8) would evaluate as FALSE. Without the NOT operator

the statement 10 > 8 would be true. NOT operator returns opposite of this. One can effectively use this operator in situations such as performing a read loop while not (eof).

If gender='M' AND age >18 then writeln ('Registration required');

AND operator returns a value of TRUE only if both conditions are true.

F AND F = F

F AND T = F

T AND F = F

T AND T = T

If age <1 or age >80 then writeln ('Soft food required.');

OR operator returns a value of TRUE if either of the conditions is met.

F OR F = F

F OR T = T

T OR F = T

T OR T = T

XOR operator returns true only if both conditions are unlike.

T XOR T = F

T XOR F = T

F XOR T = T

F XOR F = F

NOT operator returns the opposite.

not (True) = False

not (False) = True

Just like mathematical operators, you must observe precedence rules with Boolean operators. Here is precedence order:

not

and

or

ASSIGNMENTS FOR CHAPTER 4

1. Write a program to decide if the current year is a leap year. For this assignment assume that if a year can be divided by four with no remainder, then it is a leap year. To do this you have to use the mode operator (If year mod 4 = 0 then leapYear := true).

2. Write a program to read a temperature and then do the following.

If temperature = 0 then write ('freezing');

If temperature is between 20 and 25 then write ('room temperature');

If temperature = 37 then write ('body temperature');

If temperature = 100 then write ('boiling point');

Use CASE structure to do this.

3. By now you should be able to sit down and write small programs without referring to any notes or books. If you can't do this yet, you should practice writing programs to add, subtract, multiply, etc.

Now write a program to read one number, then read an arithmetic operator as a character, then read a second number, as follows:

readln(firstNumber);

readln(Operator);

readln(SecondNumber);

Using the CASE structure you should be able to add, subtract, multiply or divide based on the operator read.

Most of this program is provided for you on the next page (Program 4-7). Complete this program.

PROGRAM 4-7

Program calculator (input, output);

var

firstNumber, SecondNumber, Result : real;

operator : char;

begin

{write introduction and instructions}

writeln('This program will add, subtract, multiply, or

writeln('divide two numbers. It is ask for one number, ');

writeln(' then the operator (only enter +, -, *, or /) ');

writeln(' and finally for the second number.');

{ask for numbers and the operator}

writeln;

write('Enter a number ');readln(firstNumber);

write('Operator ');readln(operator);

write('Enter second number ');readln(secondNumber);

{do the calculation based on the operator}

CASE operator of

'+' : result := firstnumber + secondNumber;

'-' : ____________________________________;

'*' : ____________________________________;

'/' : ____________________________________;

else

begin

writeln ('I do not recognize that operator!');

result := 0;

end;

end; {end the case}

writeln ('The result is: ',result:9:2)

end.

 

Program run:

This program will add, subtract, multiply, or

divide two numbers. It is ask for one number,

then the operator (only enter +, -, *, or /)

and finally for the second number.

Enter a number 15

Operator *

Enter second number 10

The result is: 150.00

This program will add, subtract, multiply, or

divide two numbers. It is ask for one number,

then the operator (only enter +, -, *, or /)

and finally for the second number.

Enter a number 11

Operator /

Enter second number 2

The result is: 5.50

Type EXIT to return to Turbo Pascal...

 

This program will add, subtract, multiply, or

divide two numbers. It is ask for one number,

then the operator (only enter +, -, *, or /)

and finally for the second number.

Enter a number 75

Operator -

Enter second number 50

The result is: 25.00

Microsoft(R) MS-DOS(R) Version 5.00

(C)Copyright Microsoft Corp 1981-1991.