|
To access the contents, click the chapter and section titles.
Learn Pascal in a Three Days (2nd Ed.)
Example: The FactorialThe factorial of a positive integer N is defined as: N! = N * (N-1) * (N-2)... * 3 * 2 * 1 Thus the factorial of 4 is 4 * 3 * 2 * 1, and the factorial of 3 is 3 * 2 * 1. You can then express the following relationships for the factorial: 4! = 4 * 3! 3! = 3 * 2! 2! = 2 * 1! 1! = 1 In general, you can write the following Pascal statement to calculate the factorial using a counter: Factorial := Factorial * Kounter; The variable Kounter can be incremented from 1 to N or decremented from N to 1. The following program uses this logic in a loop with a decremented step. { ------------------------------ figure 4-5 ------------------------------ } PROGRAM FactorialProg1(INPUT,OUTPUT); VAR Factorial :REAL; Kounter, Number :INTEGER; BEGIN WRITE('Give me a number, and I will tell you the factorial: '); READLN(Number); Factorial := 1; FOR kounter := Number DOWNTO 1 DO Factorial := Factorial * Kounter; WRITELN('The factorial of ', Number,' is ', Factorial:0:0); WRITELN; WRITELN('Press ENTER to continue..'); READLN END. Notice that the variable Factorial must be initialized to the value 1 before starting the iterative process. A sample run of the program gives the following: Give me a number, and I will tell you the factorial: 8 The factorial of 8 is 40320 Press ENTER to continue..
4-4 Nested LoopsLike any other statement, the FOR loop statement can be used inside another loop. In this case it is said that the inner loop is nested inside the outer loop. You can nest as many loops as you wish inside one another, according to your application. The next program displays on your screen the following array of numbers. 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 The array consists of three rows and five columns. You can control the number of rows and columns by using the counters of two nested loops. As you can see, for each round of the outer loop counter (Row), the inner loop counter (Column) loops five times. The values that appear in the output are the values of the counter Column. Notice that a blank line is displayed after a complete row is done, using the outer loop counter. { ------------------------------ figure 4-6 ------------------------------ } PROGRAM NestedLoops(OUTPUT); VAR Row, Column :INTEGER; BEGIN FOR Row := 1 TO 3 DO { Start of the outer loop } BEGIN FOR Column := 1 to 5 DO { Start of the inner loop } WRITE(Column, ' '); { End of the inner loop } WRITELN { This statement belongs to the outer loop } END { The end of the outer loop } END.
|
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. |