• Keine Ergebnisse gefunden

10. CONTROL STRUCTURES

10.3 CONDITIONAL EXECUTION

In writing programs, you usually have groups of statements that you want to be executed only if some condition has been met.

Not surprisingly, this is known as conditional execution. In Pascal, conditional execution takes the form:

i f <boolean expression>

then <statement>;

10-4

The if ... then structure works quite simply. If boolean expression returns a value of True, then statement is executed; otherwise, it is ignored. For example,

i f Score> Maximum then Maximum := Score;

will set Maximum to Score if and only if Score is greater than Maximum. You could also do the following:

NewMax := (Score> Maximum);

i f NewMax

then Maximum := Score;

If you really want to get fancy, you can do this:

i f Score> Maximum then begin Maximum:= Score;

WriteLn( 'Congratulations!');

WriteLn('Your new high score is ',Maximum) end;

Tied closely to the idea of conditional execution is that of alternation. Alternation means that one set of statements is executed if a condition is True, and another set if that condition is False. You could do it this way:

i f <condition>

then < statementl>;

if not <condition>

then <statement2>;

Pascal, however, provides a simpler way:

i f <condition>

then < statementl >

else <statement2>;

By using the if ... then ... else construct, you can amplify your example as follows:

if Score> Maximum then begin Maximum := Score;

WriteLn('Congratulations!');

WriteLn('You have set a new high score of ',Maximum) end

else begin

WriteLn('Your score was ',score);

WriteLn('Nice try, but you can do better') end;

10.4

ITERATION

Conditional execution adds a lot to your programming capabili-ties, but you still have a major handicap: You can execute each statement only once. You need the ability to repeat a section of code some number of times or until some condition is met. This looping process is known as iteration. Niklaus Wirth must have really liked loops, because Pascal has not one, not two, but three forms of iteration: for ... do, while ... do, and repeat. .. until. Let's look at each.

-Looping-10-6

10.4.1 The FOR ... DO Loop

There are situations where you want to have a statement executed some number of times. Often, you want or need to know how many times you've gone through the loop so far. Or, you might want a variable to step through a range of values, executing a statement (or group of statements) once for each value.

The for ... do loop allows you to do this. It uses the format:

for <var> := <expl> to <exp2> do

<statement>;

When the loop is encountered, var is assigned the value of exp1. If var is less than or equal to exp2, then statement is executed. var is then increased by one, and the test is repeated. This goes on until var is greater than exp2. If exp1 is greater than exp2, then statement is never executed. For example, you could write:

for Indx := 1 to 10 do

WriteLn('n = ' ,Indx,' n*n = ' ,Indx*Indx);

This will display the integers from 1 to 10, along with their squares. If you want to decrement (decrease) var instead of incrementing it, you can use the format:

for <var> := <expl> downto <exp2> do

<statement>;

Now, var decreases each time until it is less than exp2, and statement is never executed if exp1 is less than exp2.

The for ... do loop in Pascal sacrifices convenience for a gain in power. You cannot specify a step value by which to change var, as you can in most other languages. To do that, you have to create your own loop using one of the other loop constructs (described below). Also, var cannot be of type Real; again, you have to use another type of loop. .

So much for the inconvenience; where's the power? Well, var doesn't have to be of type Integer; it can be of any scalar data

type: Char, Byte, Boolean, or any declared scalar type (DST) you care to define. Given appropriate definitions, the following loops are all valid:

for Indx := 30 downto 20 do

<statement>j for Ch := 'A! to 'Z' do

< statement> j

for Flag := True downto False do

<statement>;

for Daor := Mon to Fri do

<statement>;

Nowyou can see why there is no step capability. Mixing numeric and non-numeric values could be very confusing, especially for those programmers who write compilers. Besides, there is something clumsy about a statement like

for Month:= January to December step 2 do

<statement>;

while the statement

for Month := January to December step February do

<statement>;

doesn't make any sense at all. So there is no step capability in for

loops. I

As with if ... then ... else, you can use a compound statement in place of statement, to wit:

for Indx := 20 to 30 do begin

<statement l>j

<statement n>

eDd;

10.4.2 The WHILE ... DD Loop

Since the for ... do loop can't easily meet all your iterative needs, Pascal give you two others, both controlled by boolean expres-sions. The first is the while ... do loop:

while <boolean expression> do

<statement>;

This loop will cause statement to be executed as long as boolean expression resolves to a value of True. It will never be executed at all if boolean expression is initially False.

If you wish, you can replace for ... do loops as follows:

<var> := <exp1>;

while <var> <= <exp2> do begin

<statement 1>;

<var> := succ( <var> ) end;

If you want to use a step value, then you need to change the last statement to reflect tha~. For example, to have a step value of 3, you could change the last statement in the loop to read

<var> := <var> + 3

Of course, you can do other things than imitate for loops. For example, here's a binary search program. It searches a sorted list for a given value until it either finds it or determines that it is not in the list. The advantage of a binary search is that it only takes a maximum of (n log 2) tries to search a list ofn objects. This means that a list of 1024 elements will take at most 10 tries through the loop.

procedure Bina.rySearch(DKey: ListVal;

var Index : Integer; var Found: Boolean);

{

This procedure does a binary search for DKey in List, where List = ARRAY[IMin..IMax] OF ListVal

List is sorted such that List[I] < = List[I + 1]

It searches for Index such that DKey = List[Index]

If fOWld, then Found = True else Found = False

var

Upper ,Lower : Integer;

begin

Upper := IMa.x;Lower := IMin; Found := False;

while not Found and (Lower <= Upper) do begin Index:= (Upper + Lower) DIV 2;

i f DKey < LiBt[Index]

then Upper := Pred(Index) else if DKey

>

LiBt[Index]

then Lower := Succ(Index) else Found := True

end

end.; { of proc BinarySearch }

10.4.3 The REPEAT ... UNTIL Loop

The third loop is repeat. .. until. It takes the format:

repeat

<statement 1>;

<statement 2>;

<statement n>

untU <boolean condition>;

This differs from while ... do in three important ways. First, the statements within the loop are always executed at least once. In other words, all the statements in the loop are executed before boolean condition is resolved. Second, the statements continue to execute as long as boolean condition is false; the while loop executes while boolean expression is true. Third, the repeat loop can directly execute more than one statement and, therefore, doesn't need a compound statement (begin ... end) to handle multiple statements.

One common use of repeat loops is to condition input, that is, to prompt the user for some value and to continue to prompt until the value entered is one of those that you decide to allow. For example, the following routine prompts the user to enter an

integer within the range [Iow ... high]. It repeats the prompt if (1) there is an I/O error (due to bad numeric format), or (2) the value is not within the proper range:

program TestGetInteger;

type

Prompt = striDg[80];

procedure GetInteger( var Val : Integer; Msg : Prompt;

Low,High : Integer);

begin

{$I-,R-} { turn off I/O, range checking}

repeat Write(Msg);

ReadLn(Val)

untU (IOresult=O) and (Low<=Val) and (Val<=High) {$I + ,R+} { turn everything back on }

end; { of proc GetInteger }

This provides "bulletproof" integer input. No matter what the usertries to do, this routine will continueto ask for a propervalue until the one entered has the proper format and is within the proper range.