Call a sub-routine
A sub-routine is a small algorithm with a name of its own. You write it once, and then you call it by writing its name and brackets, such as water(). At a call the main algorithm pauses. The sub-routine runs from its first line to its last, and then the main algorithm carries on with the line after the call. Words with a fixed meaning in pseudocode, such as IF, FOR and SUB-ROUTINE, are key words, so they cannot be used as names for your own variables or sub-routines. One sub-routine can be called many times, even inside a loop or an IF, so you never have to write its lines again. Pseudocode has no fixed way to declare one: SUB-ROUTINE name() ends with END SUB, PROCEDURE name() ends with ENDPROCEDURE, and DEF name() has no end word because the indentation shows where it stops. A predefined sub-routine is called in just the same way, after you import the library it lives in.
1SUB-ROUTINE water() 2 OUTPUT "Watering" 3 moisture ← moisture + 40 4END SUB 5moisture ← 20 6FOR day ← 1 TO 3 7 IF moisture < 50 THEN 8 water() 9 ENDIF 10 moisture ← moisture - 15 11NEXT day 12OUTPUT "Moisture: ", moisture
Watering Watering Moisture: 55
1SUB-ROUTINE banner() 2 OUTPUT "*****" 3END SUB 4banner() 5OUTPUT "Welcome to the club" 6banner()
***** Welcome to the club *****
| Style | First line | Last line |
|---|---|---|
| Pseudocode, version 1 | SUB-ROUTINE banner() | END SUB |
| Pseudocode, version 2 | PROCEDURE banner() | ENDPROCEDURE |
| Python style | DEF banner(): | none: the indent ends it |
| Python (real) | def banner(): | none: the indent ends it |
Helper cards (no computer). On a small card write a sub-routine, for example SUB-ROUTINE clap() with the line ‘clap twice’ and END SUB. On a big sheet write a main program of six lines that includes three calls to clap(). A partner reads the main program aloud with a finger on the current line. At every call the finger jumps to the card, does the actions, and jumps back to the line after the call. Then write a sub-routine of your own, such as stamp() or hop(), and add a FOR loop to the main sheet that calls it four times.
1SUB-ROUTINE cheer() 2 OUTPUT "Hooray!" 3END SUB 4FOR round ← 1 TO 3 5 OUTPUT "Round ", round 6 IF round = 2 THEN 7 cheer() 8 ENDIF 9NEXT round
1SUB-ROUTINE sip() 2 level ← level - 25 3END SUB 4level ← 100 5FOR n ← 1 TO 3 6 sip() 7 OUTPUT level 8NEXT n
1SUB-ROUTINE ding() 2 OUTPUT "Ding" 3END SUB 4FOR bell ← 1 TO 2 5 ding 6NEXT bell