Procedural Programming Example
Revision as of 12:51, 15 December 2015 by Jhernandez3 (talk | contribs) (Created page with "Category: Analytica User Guide <breadcrumbs> Analytica User Guide > {{PAGENAME}}</breadcrumbs><br /> The following function, Factors(), computes the prime factors of an i...")
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);
|
5 | (result := Concat(result, [n]);
|
6 | x := r)
|
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: Var v := e” on page 376 for more.- You can group several expressions (statements) into a definition by separating them by “;” (semicolons). Expressions can be on the same line or successive lines. See “Begin-End, (), and “;” for grouping expressions” on page 376.
While test Do body
construct tests conditionTest
, and, if True, evaluatesBody
, and repeats until conditionTest
is False. See “While(Test) Do Body” on page 381.- 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, (), and “;” for grouping expressions” on page 376.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: v := e” on page 377.- 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