M Web Magazine Issue 002 (March 5, 1997 to June 4, 1997)

Teach You, Teach Me

This section of MWM is a tutorial on M. You may have already read how efficient and fast it is; well why not try it out for yourself. It's as easy as they say. This tutorial assumes no knowledge of programming whatsoever. If you missed last issue, be sure to check it out.

Our tutorial is based on the Student version of Micronetics Standard M (MSM/Student). For more information about this company jump over to their web page. In order to download a copy of this program check out Chris Bonnici's Download M section. Before you leave this page be sure to bookmark it so that you can find your way back with ease.

We're new to web publishing and the section is appropriately called Teach You, Teach Me (TYTM). The reason for such a name is that we want this tutorial to be as useful to you as is possible on the web. We know what we want to pass on, but we want you, through your feedback, to guide us on this route. Your input could be in the form of general comments for the Feedback part of this e-zine. Here you can give us the green light, hit the expand-topic button and even take us back a step or two.

No two people will generate the same solution to a problem. The approach we have adopted is one we feel lies somewhere between the extremes of coding conventions though our code will lopside towards the lengthier, easier to understand programming style. We welcome any code you send in, be it different approaches to what we present here or other code of your choice. All accepted submissions will be displayed in The Library.

Last time we introduced commands to handle basic input and output, variable handling and laid out the foundations which are necessary to get one going. Today we consider looping and conditions.

Click here to download this issue's routines.

Looping

Unless specifically instructed, a program flows from top to bottom. There are occasions when we would like our program to repeat a sequence of commands. This is precisely the idea behind a loop.

FOR (may also be written as F)

The FOR command in M is used to loop through an expression. It (like many other M commands) is very versatile. The basic FOR as with other programming languages is used to loop a number of times and its syntax is:

Syntax: FOR <space> <var>=<start>:<skip>:<end> <commands>

How FOR works.

1.1 <var> assigned the value of <start>

1.2 check if <var> is greater than <end>. If it is, continue at <2.0>

1.3 The <commands> following the FOR are processed

1.4 check if <var> is equal to <end>. If it is, continue at <2.0>

1.5 Add <skip> to <var>

1.6 Continue processing from <1.3>

2.0 Process next command (FOR has terminated)

FOR001Þ ;Program to Demonstrate the FOR command - ACB - Feb 1997

Þ ;(C) M Web Magazine @ http://www.geocities.com/SiliconValley/7041/mwm.html

Þ ;You are using this program at your own risk

Þ ;

Þ READ #,"Command: FOR I=1:2:10 WRITE !,I ",*ANS:10

Þ FOR I=1:2:10 WRITE !,I

Þ HANG 5

Þ ; next example

Þ READ #,"Command: FOR I=10:-1:1 WRITE !,I ",ANS#1

Þ FOR I=10:-1:1 WRITE !,I

Þ HANG 5

Þ ; next example

Þ READ #,"Command: FOR I=10:1:1 WRITE !,I ",ANS#1:10

Þ FOR I=10:1:1 WRITE !,I

Þ QUIT

The above program (which you can download) helps demonstrate the first facet of FOR.

Using the model shown above, the FOR I=1:2:10 initializes I with the value 1 (<start>) checks that it is not greater than 10 (<end>) and since it isn't performs the WRITE command (which basically moves the cursor down 1 line and displays the value of I).

Having finished, it then adds 2 (<skip>) to I making I equal to 3 and performs the procedure again.

Without running the program, can you work out the numbers that will be displayed?

The FOR I=10:-1:1 in the program above demonstrates a decreasing loop. If the <skip> value is entered as a negative number, the FOR command assumes that the loop will commence from a large number and work its way down to a lesser value.

What numbers will be shown?

Try drawing a flowchart depicting the operation of the FOR I=10:-1:1. Express it in formal English.

The final FOR I=10:1:1 is a case of a logical error and will display no number on the screen. Why is this?

Having experienced our first encounter with FOR, the above program also has some new stuff we've never talked about:

HANG (may also be written as H)

Syntax: HANG <one space> <numeric expression>

HANG delays the computer for the time in seconds specified after the command. It is of utmost importance that between the HANG and the time there is only one space as otherwise the command interpreter will take it to mean a totally different command HALT that will exit you from the program. Both HANG and HALT share the same common short version equivalent H and in order for the interpreter to distinguish between one and the other, it looks for the time element. Even though it may sound strange, if your write HANG (in full) without a number, it is taken to mean HALT.

Some people may query the difference between a HALT and a QUIT. QUIT is used to terminate the current operation (and as shown later on in this tutorial) only returns you to the command prompt (>) if it lies in the outermost level of program execution, while HALT stops the program irrelevant of where it lies.

When the FOR I=1:1:10 loop comes to an end, what value does the variable I have? Write a program to run the loop and show I at then end.

Try setting a variable HOWMUCH to 2 (using either SET or READ) after which HANG HOWMUCH.

We first talked about READ in MWM-001, and today we talk about this command's #Length and :Timeout extensions. We mention briefly the reason for preceding a variable with an * (asterisk).

In the READ #,"Command: FOR I=1:2:10 WRITE !,I ",*ANS:10, after we clear the screen (#) and display the prompt "Command: FOR I=1:2:10 WRITE !,I ", we will wait for a total of 10 seconds until the user presses something. If nothing is pressed within this time period the READ command is terminated and the next command is processed.

The * is used to indicate that the value is the ASCII value of the key pressed and not the actual character. In MWM-003 ASCII will be one of the topics we will delve into, and for this tutorial it suffices to say that inside any computer there is a table that maps each and every character to a number (If you want to learn more about ASCII before MWM-003, try a couple of search engines). When the READ variable is preceded by a * it can only store one character within it and (besides the benefits entailed from being able to process such input) is very useful in getting programs to operate on the "Press a Single Key" concept.

The READ #,"Command: FOR I=10:-1:1 WRITE !,I ",ANS#1 also will terminate the read after a single key is pressed. This is because in this example the maximum input length is set to 1 (#1).

Finally, READ #,"Command: FOR I=10:1:1 WRITE !,I",ANS#1:10 combines timeout with maximum length conditions.

To determine the ASCII value of a character, write a program that reads a key press into an *variable and displays the result of variable (no asterisk this time). The number shown is the ASCII value of that symbol.

FOR002Þ ;Program to Demonstrate the FOR command - ACB - Feb 1997

Þ ;(C) M Web Magazine @ http://www.geocities.com/SiliconValley/7041/mwm.html

Þ ;You are using this program at your own risk

Þ ;

Þ F TXT="M","WEB","MAGAZINE","also known as","MWM" W !,TXT H 2

Þ Q

Besides numbers, FOR can also handle a list of strings separated by commas. There shouldn't be any spaces between the different string literals. The program displays the words in quotes one after the other with a little delay between them. Those who have not fully discerned the idea of a string literal (introduced in MWM-001) may point out that also known as has spaces. Looking closely, "also know as" is enclosed in one pair of quotes. This is called a string literal and is processed by the computer as one item.

FOR003Þ ;Program to Demonstrate the FOR command - ACB - Feb 1997

Þ ;(C) M Web Magazine @ http://www.geocities.com/SiliconValley/7041/mwm.html

Þ ;You are using this program at your own risk

Þ ;

Þ W #

Þ F ROW=1:1:2 W ! F COL=1:1:3 W "X" F DELAY=1:1:30000

Þ Q

Our final FOR program demonstrates a case of multiple loops one inside the other. In fact we have three FOR loops. Don't worry too much about how to interpret multiple commands on a single line; a few paragraphs down we will tackle this issue. The colored lines show how much each FOR covers. You should appreciate that each FOR enloops all the commands to its right. The outermost loop (1) loops from 1 to 2 varying the variable ROW. Each time through the loop another FOR (2) performs another loop varying variable COL incrementally from 1 to 3. Inside this loop the instruction to write on the screen an X is called up. After the X, the innermost loop (3) takes off.

We are going to dry run the entire process. The table below lists the life span of the three different FOR commands with red associated with FOR ROW, blue with FOR COL and green with FOR DELAY. We've used indentation to identify in a clearer manner the different loops being analysed. We are showing the value of the different variables that are being used in these embedded multiple loops.. The value that would have changed in that loop is show as bold. (PS. The FOR DELAY loop has been shortened out as it would necessitate too much space to show all numbers from 1 to 30000.

Active FOR

FOR Command being processed ROW COL DELAY
             
      FOR ROW=1:1:2 1 <not defined> <not defined>
      --FOR COL=1:1:3 1 1 <not defined>
      ----FOR DELAY=1:1:30000 1 1 1
      ----FOR DELAY=1:1:30000 1 1
      ----FOR DELAY=1:1:30000 1 1 30000
      ----DELAY LOOP EXITS      
      --FOR COL=1:1:3 1 2 30000
      ----FOR DELAY=1:1:30000 1 2 1
      ----FOR DELAY=1:1:30000 1 2
      ----FOR DELAY=1:1:30000 1 2 30000
      ----DELAY LOOP EXITS      
      --FOR COL=1:1:3 1 3 30000
      ----FOR DELAY=1:1:30000 1 3 1
      ----FOR DELAY=1:1:30000 1 3
      ----FOR DELAY=1:1:30000 1 3 30000
      ----DELAY LOOP EXITS      
      --COL LOOP EXITS      
      FOR ROW=1:1:2 2 3 30000
      --FOR COL=1:1:3 2 1 30000
      ----FOR DELAY=1:1:30000 2 1 1
      ----FOR DELAY=1:1:30000 2 1
      ----FOR DELAY=1:1:30000 2 1 30000
      ----DELAY LOOP EXITS      
      --FOR COL=1:1:3 2 2 30000
      ----FOR DELAY=1:1:30000 2 2 1
      ----FOR DELAY=1:1:30000 2 2
      ----FOR DELAY=1:1:30000 2 2 30000
      ----DELAY LOOP EXITS      
      --FOR COL=1:1:3 2 3 30000
      ----FOR DELAY=1:1:30000 2 3 1
      ----FOR DELAY=1:1:30000 2 3
      ----FOR DELAY=1:1:30000 2 3 30000
      ----DELAY LOOP EXITS      
      --COL LOOP EXITS      
      ROW LOOP EXITS      

It might seem complex at first, but it's simple as the clock sitting close by. Your watch works as follows (though we hope you didn't pay too much for it J ):

FOR HOURS=1:1:24 FOR MINUTES=1:1:60 FOR SECONDS=1:1:60 W !,"Tick-Tock"

In order for the minutes counter to up one, the seconds counter must loop 60 times. For the hours counter to loop, the minutes counter must have looped 60 times.

We've used a FOR command to simulate a delay (practically we instructed the computer to perform a loop 30000 times doing nothing). This type of delay is quite unreliable as it depends a lot on the speed of the computer executing it (the faster the computer, the quicker the loop will come to an end). So normally we use the HANG command. Write a program that performs a 1 second delay on your computer using a FOR command. (Hint: Initially time 5 seconds and then divide accordingly; use a READ command to start the timer and a WRITE to indicate that the loop is over).

In the clock example, how many times will the phrase "Tick-Tock" be displayed?

Write a program that sets a variable (say CNT equal to zero). Replace W !,"Tick-Tock" with SET CNT=CNT+1. On the line following the looped FOR's display the value of CNT. This will answer the question above.

Write a program that displays the multiplication tables from 1 to 10.

In our dry run of the embedded loops we used the term <not defined>. This is a common convention to indicate that at that point, the variable has no known value or that the variable does not exist at that stage of the program. You'll get an error if you try to reference an undefined variable (try it out: type WRITE NOTDEF in direct mode and see what happens)

Program Control

Programs flow from top to bottom and perform an action. With loops we sometimes go round some lines, but ultimately always end up filtering through the same operation. There are many cases were we have to implement "reasoning" into our programs, reasoning based on the state of things at the instance we apply the check. In a computer it simply means that one tests for particular conditions (normally a value inside a variable) and perform lines of code accordingly. A very easy to understand example is the printing of Ms or Mr depending on whether the value entered inside a person's sex field is F or M.

IF (may also be written as I)

This command allows programs to perform decisions. On similar lines to what living beings perform a multitude of times daily the most fundamental form of decision making is that of choosing whether to do something or not. In order to choose/not choose something, we must have a condition that weighs the balance towards one side or the other.

For example, to a little creature that likes darkness, its DNA might tell it that:

IF <light is on> <hide>.

With computers there is basically not difference, other than maybe changing conditions and decisions (although if a light sensor is attached to a computer one would be able to enquire <light is on>).

Syntax: IF< space> <condition><space><commands>

IF001Þ ;How IF works - ACB - Feb 1997 [ 02/02/97 10:08 AM ]

Þ ;(C) M Web Magazine @ http://www.geocities.com/SiliconValley/7041/mwm.html

Þ ;You are using this program at your own risk

Þ ;

Þ W #

10Þ R !,"Enter Password: ",PASS

Þ IF (PASS'="M-TECH") GO 10

Þ W #,"Welcome"

Þ Q

 

In the program IF001, after displaying the prompt "Enter Password: ", we input a string into the variable PASS. The IF condition is then used to check whether the value stored in PASS is not equal to "M-TECH". If they are not equal the command GO 10 is then processed and the program loops to label 10. If the valid password is entered the program Welcomes the user and stops.

 

GO (may be written as G)

This command is GO is probably the most debated command of all computer instructions. It is know generically as a jump. It is the command most associated with spaghetti programming and in many discussions where it is brought up, strong debate can reign. GO is probably one of the simplest commands around. It transfers program control to the command at the beginning of the label jumped to. When abused, programs written with GO's can be very difficult to understand and the diagram adjacent can help to explain why. Imagine you are trying to follow a 6 page program that takes you from page 1 to page 4, then from page 4 to 3, then from 3 to 6, then from 6 to 2, then from … So much energy will be spent flipping pages and finding line labels that very little will remain actually understanding what the program does.

With some programming languages, it is very easy to write programs without the use of jump statements. M does not classify with this group and while it may theoretically possible to write programs that don't make use of GO's with large programs GO's become necessary.

We would like to point out that we do not agree with the statement that using GO's will lead to unmaintainable code and blame this association on:

As a programmer what should you always keep in mind:

In the program below, we provide the same visual solution as with IF001, but use a different approach (besides reintroducing another aspect of the FOR command). As you can see, we can cause loops without using GO's.

IF002Þ ;How IF works - ACB - Feb 1997 [ 02/02/97 10:03 AM ]

Þ ;(C) M Web Magazine @ http://www.geocities.com/SiliconValley/7041/mwm.html

Þ ;You are using this program at your own risk

Þ ;

Þ W #

Þ F R !,"Enter Password: ",PASS IF (PASS="M-TECH") Q

Þ W #,"Welcome"

Þ Q

So we removed the GO, but is this solution better? Don't panic. It's still M, the only difference here is that one of the lines has more than one command and is doing a multitude of stuff. It appears cryptic, but with a little clear minded analysis the cryptic will be buried, leaving the code. After all, if you don't know Chinese, Chinese writing will appear cryptic, yet more than one billion people manage it quite nicely.

F R !,"Enter Password: ",PASS IF (PASS="M-TECH") Q

The line above shows the different commands fitted into the line. They have been color coded to improve clarity:

 

FOR <space><space> (written as F <space><space>)

The FOR presented above is used to cause an endless loop. An endless loop condition is one which will, if unchecked, cause the program to continually go round and round, passing though the same commands. An endless loop constitutes a form of program error (after all we do want a program to come to an end sometime).

All commands to the right of the FOR will be executed continually. And in IF002, we have two such commands; a READ (written as R)and an IF. The READ should be quite easy to decipher; the IF is also straight forward.

To go out of an endless loop, we use the command QUIT (written as Q). A QUIT inside the body of a FOR causes the FOR to exit, control passing to the next line. The line we are talking about will loop until the password entered by the program user (and stored in the variable PASS) is equal to "M-TECH" (IF variable PASS is "M-TECH" the loop exits).

A few paragraphs up we talked about the difference between QUIT and HALT. Try replacing QUIT with HANG and see what's different.

IF003Þ ;Post conditionals - ACB - Feb 1997

Þ ;(C) M Web Magazine @ http://www.geocities.com/SiliconValley/7041/mwm.html

Þ ;You are using this program at your own risk

Þ ;

Þ W #

THISONEÞ F R !,"Enter Password: ",PASS Q:(PASS="M-TECH") W !,"Invalid"

Þ W #,"Welcome"

Þ Q

 

Try splitting line THISONE into the different commands on the line (hint: we've put two spaces between the different parts).

If you take a close look at the line you will notice that the IF command has gone. It has been replaced with Q:(PASS="M-TECH"). M is probably one of the few languages that can take what are know as Post Conditionals. This means that a command will only be executed if the condition associated with the command is true. We read the command as "quit if variable PASS is equal to M-TECH".

Post conditionals are not right bound. With an IF command, anything to the right of the IF is bound by the IF. Since post conditions apply only to the command to which they are stuck (using the colon), they will not effect other commands on the line. In the program above, if the condition PASS="M-TECH is not TRUE, the QUIT will not go into effect (i.e. it will not exit the FOR loop) and the command W !,"Invalid" is performed.

From program (IF003), there are a few points we feel are important:

1. Program flow.

It can help us understand that different commands on a line are processed left to right. Proof to this is that after the FOR (having no visible effect initially), the READ is performed first. If a correct password is entered the WRITE never goes into effect as the QUIT would have exited the loop, thereby proving that the FOR is already in effect. On the other hand if the password is not good, the QUIT never goes into effect and the WRITE goes to work. Following the WRITE, the FOR loops again and we are asked to input the password.

2. One space, two spaces.

The hint given in IF003 that different command have two spaces not one can also be used to help you settle in with multiple commands on each line. Please be aware that we put two spaces between compound commands and not within a particular command. For example you cannot put two spaces between the READ and the !,… associated with it; you can only put two spaces after the READ together with all the parts related to it). There are exceptions to this rule that will cause problems, for example a HANG will become a HALT with two spaces after it.

3. One space, two spaces.

While we have stated out a method of how to make the code more readable, we feel that we should point out where you would actually need two spaces in the program and where one would suffice. Two spaces are needed after the:

4. If you every need to manually terminate a loop (or for that matter any running program), maybe because it is in an endless loop, hold the control key down and press C (written as CTRL+C).

Try modifying IF003 so that you can remove the unnecessary spaces.

 

Use the following Formal-English statements to write the program requested:

1.0 Display the prompt "Enter number of Students" and store into a variable NUM the user's input.

2.0 Initialize a variable TOTAL with zero.

3.0 Loop the number of times specified in NUM, each time

3.1 Display the student number

3.2 Ask for a mark

3.3 Add the mark entered to the variable TOTAL

4.0 Display the Total Mark (TOTAL) and the average mark (TOTAL/NUM)

 

Draw a Flowchart for the above program

 

IF004Þ ;Conditional Loops - ACB - Feb 1997

Þ ;(C) M Web Magazine @ http://www.geocities.com/SiliconValley/7041/mwm.html

Þ ;You are using this program at your own risk

Þ ;

Þ W #,"Program Section 1"

Þ S MONEY=0

Þ F Q:(MONEY=0) R !,"How much money do you have (0 - exit)? ",MONEY

Þ ;

Þ W !!,"Program Section 2"

Þ S MONEY=0

Þ F R !,"How much money do you have (0 - exit)? ",MONEY Q:(MONEY=0)

Þ Q

 

The program above has two quasi-identical sections. In the two "parts" the only difference is the position of Q:(MONEY=0) part. Run the program and observe what happens. Why does one part not "work"? Draw flowcharts (or use formal English) of the two FOR parts. Correct the problem part without altering the FOR lines.

If you would like MWM to review and publish your solution (or comment on any difficulties you've encountered) please e-mail us.

Goodbye

We'll stop here today and hope that the material we've covered today allows you to explore computing arenas possible up to know. Practice make perfect and programming is no exception; the more you code the more you better yourself. And don't forget, send in your code so that we can share it with others (if special conditions to the use of the software apply, please send them in with the programs).

Commands we looked at today: FOR, IF, GO, HALT, HANG and post conditions and the length and time-out parameters of the READ command.

Operators

Relational operators are those symbols that must be used to compare the relation of something to another. The list below summarizes them

Operator Name Example
= Equal to OPTION=1
> Greater Than AGE>21
< Less than BALANCE<1000
[ String Contains "Yy"[CHOICE
] String Follows "1234567"]ACCNO
? Pattern Match discussed in a future issue
]] String Sorts After GRADE1]]GRADE2

Logic Operators (as they are presented here) allow us to join together different conditions so as to get one compound expression. These are 100% equivalent to the phrases we use daily:

Operator Name Example
& AND (X=0)&(Y=0)
! OR (PAYMENT="OVERDUE")!(BAL>CREDIT)
NOT (PASS'="M-TECH")

One important point worth mentioning is that the NOT can be used with logic and relational operators to reverse the meaning of the expression. The main problem is that people find it quite difficult to reason out this operator (maybe because we are brought up to think positive).

Well the little trick which follows should alleviate the problem. When reasoning out a not, remove it and determine what the positive aspect means. For example, AGE'>15 would become AGE>15. This implies all ages from 16 onwards (for simplicity we are working with integers).

To find out the range of the NOT, place it in the expression and take the exact opposite. This would end up meaning that AGE'>15 means all ages up to and including 15.

Last time we talked about the Math Operators, today we formalize the list

Operator Name Example
+ Addition 3+2 (gives 5)
- Subtraction 3-2 (gives 1)
* Multiplication 3*2 (gives 6)
/ Division 3/2 (gives 1.5)
** Exponentiation 3**2 (3 to the power of 2 gives 9)
\ Integer Division 3\2 gives 1
# Modulus 3#2 remainder 1

Besides Operators that can work with numbers, we also have string operators. These are used to manipulate string data.

Operator Name Example
_ Concatenate (join) "HELLO "_"WORLD" (gives HELLO WORLD)

Armed with these operators, you should now be able to open up your world of computing. It may be wise to experiment in direct mode initially (until you get the hang of things) and once you've mastered some of the commands, a whole new world of computing is at your fingers.

Flowcharts

A flowchart allows one to show a pictorial representation of the program (or part of it). It is not the only method available (we have also used another method here normally referred to as formal English. With formal English, program functionality is explained using point annotated phrases. The most pronounced claims against flowcharts is that it's symbols do not reflect some of the language constructs that entered programming languages (M included) at a later stage plus flowcharts tend to encourage the use of GO's.

Why did we choose Flowcharts then? First, flowcharts will serve our purpose quite nicely and secondly the flowchart is still probably the most commonly used means of pictorial representation. We hope to mention other methods of program representation in the future.

Without delving too deep in this area, a flowchart uses symbols to demonstrate program flow.

Program Start or Stop. A program would contain a start or end. This oval normally appears twice in a program; at the beginning with an arrow going out of it and at the end with an arrow coming into it. Only one arrow flows in or out of the program.

Process. This rectangle is used to demonstrate an internal calculation within a program or the setting of a variable.

Input / Output. Anything read into a program or anything written by a program goes into this shape.

Decision. This symbol is unique in that it has one input and two outputs. Being a decision, a computer will be presented with a condition. The condition may end up being TRUE (Yes) or FALSE (No). Depending on this result, program flow follows the appropriate line.

External Routine. We use this shape to show that the content of that box constitutes a compound process. These boxes may be opened up to give entire flowcharts themselves. These symbols make it possible to control the size and focus of a program. For example a complex validation routine may be focused upon in a separate flowchart, thereby allowing the calling program to focus on other aspects of the general program.

The symbols mentioned here must be joined together using lines with arrows indicating direction. This allows one to follow program flow.

Pass on our Web Address!

E&OE

Next Page

Up/TOC

 

1