Procedural Programming Example
Revision as of 03:31, 29 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 DO
4 BEGIN
2 VAR r := Floor(x/n);
IF r*n = x THEN
5 (result := Concat(result, [n]);
6 x := r)
ELSE n := n + 1
4,7 END; /* End While loop */
7, 8 result /* End Definition */
This definition illustrates these features:
VAR x := e
construct 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 body
construct tests conditionTest
, and, if True, evaluatesBody
, and repeats until conditionTest
is False. See While(Test) Do Body.- Begin
e1; e2; … End
groups 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 := e
lets you assign the value of an expressione
to a local variablex
or, 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
Factors
returns 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