|
To access the contents, click the chapter and section titles.
Learn Pascal in a Three Days (2nd Ed.)
As you can see in the form, this loop is ready to execute more than one statement without using the BEGIN-END blocks. Another difference between the WHILE loop and the REPEAT loop is that the REPEAT loop is executed at least once, regardless of the condition, because it starts each round by executing the statements and ends by testing the condition. In some applications this feature is necessary. Look at the factorial algorithm using a REPEAT loop: ... Factorial := 1; Kounter := Number; REPEAT Factorial := Factorial * Kounter; Kounter := Kounter - 1; UNTIL Kounter = 0; When the Kounter reaches zero (which means that the value 1 was already used up), no other rounds are needed, and the loop is terminated. You may also use the stepping-up algorithm, thus: ... Factorial := 1; Kounter := 1; REPEAT Factorial := Factorial * Kounter; Kounter := Kounter + 1; UNTIL Kounter = Number + 1; In this case the loop is terminated when the value of Kounter reaches Number+1, which means that the value Number was already used up. In the following program this REPEAT loop is nested in a WHILE loop. The program will be repeatedly executed until you enter 0 to terminate it. { ------------------------------ figure 4-9 ------------------------------ } PROGRAM FactorialProg2(INPUT,OUTPUT); VAR Factorial :REAL; Kounter, Number :INTEGER; BEGIN WRITE('Give me a number (or 0 to exit): '); READLN(Number); WHILE Number <> 0 DO { Start of the WHILE loop } BEGIN Factorial := 1; Kounter := 1; REPEAT { Start of the REPEAT loop } Factorial := Factorial * Kounter; Kounter := Kounter + 1; UNTIL Kounter = Number + 1; { End of the REPEAT loop } WRITELN('The factorial of ', Number,' is ', Factorial:0:0); WRITE('Give me a number (or 0 to exit): '); READLN(Number) END; { End of the WHILE loop } WRITELN('I am out of here!') END. Notice here that two similar input statements are used, one before the WHILE loop and one inside it. The first one is used to initialize the variable Kounter before entering the loop, in order to be ready for testing within the loop. A sample run of the program gives the following: Give me a number (or 0 to exit): 3 The factorial of 3 is 6 Give me a number (or 0 to exit): 5 The factorial of 5 is 120 Give me a number (or 0 to exit): 0 I am out of here! SummaryIn this chapter you were introduced to three control structures used to build loops. These structures are:
|
Products | Contact Us | About Us | Privacy | Ad Info | Home
Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement. |