Loop Example: Nested Loops

Home, Up: Loop and Script Examples

 

In this example:

PROMPT, BUFFER, Loop Indices, ENDLOOP.

 

Two important facts about nested loops in Hypatia:

- They ae not possible.

- You can still have them.

 

If you know any programming languages, you're probably familiar with something like this (the actual syntax varies between languages):

FOR I1 = 1 TO N1

  FOR I2 = 1 TO N2

    . . .

  NEXT

NEXT

 

You cannot do this in Hypatia -- a loop can call a script, and in this script you can use the loop index I, but the script cannot (directly or indirectly) contain another loop.

What you can do, though, is create your own loop variables, and these can be nested.

As a simple example that shows how this works, let's create a multiplication table. This is done row by row -- the outer loop variable are the rows, and the inner loop variable the columns.

At the start the script will ask how many rows and how many columns our table shall have.

Buffer mode gets started, and both the row and column indices are set to 1.

Now the nested loops begin:

If the column index is 1, a line break is written to the buffer (when the buffer is empty, this gets ignored).

The calculation that uses the two indices is performed, the result gets written to the buffer in accumulation mode -- of course, what you do with the nested loops may be more complex than the simple multiplication we use in our example.

The column index is increased by 1.

If this makes the column index exceed its maximum, it is set back to 1, and the row index is increased by 1.

If the column index exceeds its maximum, the loop is ended, and a message is displayed.

The script, let's call the script file mtable, could look like this:

 

I1: PROMPT $nrows Enter number of rows for multiplication table:

I1: PROMPT $ncols Enter number of columns:

I1: BUFFER START

I1: $row = 1

I1: $col = 1

IF $col 1 == THEN &&

$row $col * &

$col = $col 1 +

IF $col $ncols >> THEN $col = 1

ALSO: $row = $row 1 +

IF $row $nrows >> THEN ENDLOOP

I*: # The multiplication table is stored in the result buffer

I*: # Save it to a file with the command BUFFER SAVE filename

 

(Alternatively the script could save the buffer to a file, but then the file name would have to be specified in the script.)

Call this script in an infinite loop:

_*mtable

(which is short for DO * :: _mtable which is short for DO * :: RUN mtable) and afterwards save the buffer to a file.

If you open that file in an editor the columns will not be properly aligned -- you'd have to replace spaces with commas and then open the file in a program that understands CSV (comma-separated values), but for demonstrating nested loops in Hypatia, we've done well enough.

 

Home, Up: Loop and Script Examples, Prev: Loop Example: Iteration (Babylonian Root), Next: Loop Example: Monte Carlo Experiment