Iteration is achieved in Pascal using one of three main constructs. The while construct permits iteration where the number of times the iteration will be performed is undetermined, and may be carried out zero times. The repeat...until construct is used in similar circumstances, except where the iteration will be carried out at least once. The for construct is used when a task will be performed a determinate number of times. We have already seen the while construct perform a loop whilst reading through the records in the address file (see readaddr.pas). The while construct The while statement takes the form While (condition) do Begin Commands; End. Condition is evaluated before the block commands is executed. If condition evaluates to be false, then the commands sequence will never be executed and the compiler will skip to the next command after the begin...end block. If condition evaluates to be true, commands is executed repeatedly until condition evaluates to be false. Example Below is an example of a Pascal program using a while loop. It is a modification of the temperature conversion program we developed earlier. In this case we show, for a range of celsius temperatures, what the farenheit equivalent is. program devconv2; var celsius, max_celsius, increment, farenheit : real; begin celsius := 5; max_celsius := 105; increment := 10; writeln ('Temperature Conversion Chart'); writeln ('Celsius Farenheit'); while (celsius <= max_celsius) do begin farenheit := 32 + (celsius * 9 / 5); writeln (celsius:7:2,' ',farenheit:9:2); celsius := celsius + increment; end end. Here the while loop prints the farenheit equivalent of the celsius temperature while the celsius temperature is below max_celsius. At the end of the while loop, the celsius temperature increases by the value in the variable increment. The while condition evaluates to false when celsius exceeds max_celsius, in this case defined as 105. The widths used to for the numbers in the writeln command are chosen to align the numbers under the 'Celsius' and 'Farenheit' headings. The while construct could also be used in out program for writing to the paddress.txt file. As it is coded in writeadd.pas, the program has to be invoked each time it is wished to add a new record to the file. We can easily modify it using a while loop to continue to accept new records until the user chooses to exit, as below : program writeaddress; { sizes for the fields to be stored in the file } const namesize = 30; const addresssize = 30; const telnosize = 30; { record structure for the file } type address_record = record name : string[namesize]; address : string[addresssize]; email_address : string[addresssize]; telno : string[telnosize]; end; var address_rec : address_record; var outfile : text; var addrec : char; begin { open the file and prepare to append to existing records } assign (outfile, 'c:\paddress.txt'); append (outfile); writeln ('Enter a new record ? (Y for yes)'); readln (addrec); while ((addrec = 'Y') OR (addrec = 'y')) do begin { get field data from the user } write ('Enter Name : '); readln (address_rec.name); write ('Enter address for ',address_rec.name,' : '); readln (address_rec.address); write ('Enter Email address for ',address_rec.name,' : '); readln (address_rec.email_address); write ('Enter Telephone Number for ', address_rec.name,' : '); readln (address_rec.telno); {write the field data to the file } with address_rec do begin write (outfile,name,','); write (outfile,address,','); write (outfile,email_address,','); writeln (outfile,telno); end; writeln (''); writeln ('Enter a new record ? (Y for yes)'); readln (addrec); end; {end of while(addrec = 'y' or 'Y') } close (outfile); end. The repeat...until construct As mentioned in the introduction to this section, the repeat...until construct is used in similar situations to the while construct, indeed it could easily have been used in the example above using the program to write to the paddress.txt file. We provide a trivial example below where the program asks for user input in a given range. Should the user enter invalid data, the question is repeated until the user enters valid data. program showuntil; var i : integer; begin repeat writeln ('Enter a digit between 10 and 100 '); readln (i); until ((i >= 10) and (i <= 100)); writeln ('The number you entered was ', i); end. The for construct The for loop performs an iteration a determinate number of times. The number of times the repetition is performed may be a hardcoded number, or may be the value of a variable. The for loop takes either one of the following formats : Format 1 : For i := startvalue to endvalue do Begin Commands; End; Format 2: For i := endvalue downto startvalue do Begin Commands; End; In format 1, the command block is executed repeatedly and startvalue incremented by one on each repetition until startvalue = endvalue. The command block is then executed for the last time and the for loop exited. In format 2, the same sequence of events takes place except that endvalue is decremented by one on each iteration until endvalue = startvalue. The simplest for loop is as follows : For i:= 1 to 1 do Begin Commands; End This creates an infinite loop as the start and end values never change. The sequence of commands will be executed forever. Example In the example below, we use a for loop to calculate the average of and the standard deviation of a range of numbers. This program uses some features we have not used before, notably using an array of numbers (see the section on Arrays and Structures), and using the built in square root functions and random number generator. Two for loops are used - the first to populate the number array with random numbers between 1 and HIGHNUM. The average of the array is shown at the end of this for loop. The second for loop is used to calculate S(x - mean(x))2 as the numerator in the standard deviation calculation. For any mathematicians reading, we use n as a denominator rather than n-1 so the standard deviation assumes a population rather than a sample. program calcstats; const sample = 3; const highnum = 100; type numarray = array[1..sample] of integer; var nums : numarray; var ctr : integer; var total, sumdiff, average, stdev, diff : real; begin total := 0; sumdiff := 0; randomize; write ('Sampled numbers : '); for ctr := 1 to sample do begin nums[ctr] := random(highnum); write (nums[ctr],' '); total := total + nums[ctr]; end; writeln(''); { Throw a new line after listing sampled numbers } average := total / sample; writeln ('Average : ', average:10:4); { Calculate Standard Deviation } for ctr := 1 to sample do begin diff := nums[ctr] - average; sumdiff := sumdiff + (diff * diff); end; stdev := sqrt (sumdiff / sample); writeln ('Standard Deviation : ', stdev:10:4); end. This program is easily amended to populate the array of numbers by user input rather than operating on a set of randomly generated numbers. Nested Loops It is possible to nest loops, where for each iteration of an outer loop, an inner loop starts and runs to completion before the next iteration of the outer loop. This would take the form : For i : = 1 to ilimit do For j := 1 to jlimit do Begin Commands End; Assuming that jlimit was independent of the outer "i" loop, the command sequence would be executed a total of ilimit * jlimit times. A trivial example is used to illustrate, generating the multiplication tables up to 4. program showtimestables; var i, j, ilim, jlim : integer; begin ilim := 4; jlim := 4; for i := 1 to ilim do for j := 1 to jlim do writeln (i,' * ',j,' = ', i * j); end.
Hosted by www.Geocities.ws

1