|
To access the contents, click the chapter and section titles.
Learn Pascal in a Three Days (2nd Ed.)
7-6 RecursionA function or procedure may call itself, a property called recursion. The factorial function is a good example of recursion. You know (from Chapter 4) that the factorial of a number X can be obtained from the relation: factorial(X) = X * factorial(X-1) In other words, to get the factorial of 4 you multiply 4 by the factorial of 3; to get the factorial of 3 you multiply 3 by the factorial of 2, etc. This continues until you reach the value 1. Here is the program that contains the factorial function. { -------------------- figure 7-8 -------------------- } PROGRAM FunctionRecursion(INPUT, OUTPUT); VAR A:INTEGER; { ----------- Function Definition ------------ } FUNCTION Factorial(X:INTEGER):REAL; BEGIN IF X <= 1 THEN Factorial:= 1 ELSE Factorial:= X * Factorial(X-1); END; { --------------- End of Function ---------------- } { ----------------- Main program ----------------- } BEGIN WRITE('Enter a number: '); READLN(A); WRITELN('The Factorial of ', A,' = ', Factorial(A):0:0) END. Sample run: Enter a number: 6 The Factorial of 6 = 720 Notice in the function program that in the statement: Factorial:= X * Factorial(X-1); the left side contains the name of the function, while in the right side there is a call of the function to calculate the factorial of X-1. This process will continue until the condition terminates the function.
SummaryIn this chapter you learned about the Pascal program structure. You know how to divide your program into subprograms, whether functions or procedures. These are important points to remember:
|
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. |