Procedural Programming Example
Revision as of 12:53, 20 December 2015 by Jhernandez3 (talk | contribs)
The following function, Factors(), computes the prime factors of an integer x. It illustrates many of the key constructs of procedural programming.
See below for an explanation of each of these constructs, and cross references to where they are.
Numbers identify
features below
Function Factors(x)
Definition:
1 VAR result := [1];2 VAR n := 2;3 WHILE n <= x DO4 BEGIN2 VAR r := Floor(x/n);IF r*n = x THEN5 (result := Concat(result, [n]);6 x := r)ELSE n := n + 14,7 END; /* End While loop */7, 8 result /* End Definition */
This definition illustrates these features:
VAR x := econstruct defines a local variable x, and sets an initial value e. See Defining a Local Variable.- You can group several expressions (statements) into a definition by separating them using “;” (semicolons). Expressions can be on the same line or successive lines. See Begin-End for Grouping Expressions.
While test Do bodyconstruct tests conditionTest, and, if True, evaluatesBody, and repeats until conditionTestis False. See While(Test) Do Body.- Begin
e1; e2; … Endgroups several expressions separated by semicolons “;” — in this case as the body of a While loop. See “Begin-End, (), and “;” for grouping expressions” on page 376. (e1; e2; …)is another way to group expressions — in this case, as the action to be taken in the Then case. See Begin-End for Grouping Expressions.x := elets you assign the value of an expressioneto a local variablexor, as in the first case, to a parameter of a function. See Assigning to a local variable.- A comment is enclosed between /* and */ as an alternative to { and }.
- A group of expressions returns the value of the last expression — here the function
Factorsreturns the value ofresult— whether the group is delimited by Begin and End, by parentheses marks ( and ), or, as here, by nothing.
Comments
Enable comment auto-refresher