A Foretaste of Procedures - Pascal programming

In the last program example, Triangle, we have invoked a procedure from
library IntLib. To be able to do that the IntLib library must have been defined by another programmer, and the procedure must have been completely defined. Defining procedures in Pascal is not very different from writing programs. Remember that procedures are subprograms corresponding to subalgorithms. Subprograms have a form similar to programs as they have a header, a declarations part and a body.

Let’s implement the algorithm developed for the game of Fifty in the Principles. That solution used a subalgorithm Turn Of Player which must be translated into a Pascal procedure. We’ve done so in Figure which shows the corresponding program with numbered lines to facilitate references.

The program of Fifty

The main program is found in lines 22 to 36. It initializes the scores (lines 23 24), repeatedly invokes TurnOfPlayer (lines 25-28) until one of the scores is greater than or equal to 50. Finally a message is displayed indicating the winner (lines 29-35). The subalgorithm TurnOfPlayer has been packaged into a procedure (lines 6- 20) which includes a header giving the name of the procedure and its parameter, the declaration of two integer variables representing the two dice, and the actions of the subalgorithm. The procedure appears before the main program as it is a declaration: in order to use a procedure we must declare it beforehand or import it from a library as we did in the triangle program.

The procedure simulates two throws of each die by using standard function Random, as we have already done in the ChallengeGuess example. If the throws bring up a double, the score is modified accordingly. The statements of a procedure are similar to the statements of a program, they are ended with an END statement which is followed by a semicolon and not a period. We’ll present formally procedures and functions in the next chapters, so do not become anxious if things are still a little murky, this example is only intended to show you that there are neither mysteries nor magic in programming.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Pascal programming Topics