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...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


The following function, Factors(), computes the prime factors of an integer x. It illustrates many of the key constructs of procedural programming.

Example1.png

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:

  1. 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.
  2. 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.
  3. While test Do body construct tests condition Test, and, if True, evaluates Body, and repeats until condition Test is False. See “While(Test) Do Body” on page 381.
  4. 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.
  5. (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.
  6. x := e lets you assign the value of an expression e to a local variable x or, as in the first case, to a parameter of a function. See “Assigning to a local variable: v := e” on page 377.
  7. A comment is enclosed between /* and */ as an alternative to { and }.
  8. A group of expressions returns the value of the last expression — here the function Factors returns the value of result — whether the group is delimited by Begin and End, by parentheses marks ( and ), or, as here, by nothing.
Comments


You are not allowed to post comments.