TweetFollow Us on Twitter

Volume Number:2
Issue Number:2
Column Tag:Special Projects

Subprograms in Basic Explained

By Mike Steiner, Sierra Vista, AZ, MacTutor Contributing Editor

Versatile Input Routine

So, you are writing a program in Microsoft BASIC and the user of the program has to supply information for the program to process. The tradtional, and - before Microsoft BASIC for the Macintosh - sometimes the only available, way for a BASIC program to obtain data from the keyboard is via the INPUT statement. This yeoman method has worked for many years and has proven its worth. It also has shown all its faults. In some varieties of BASIC, certain characters (notably the comma and colon) cannot be read by INPUT. Unless you incorporate error checking routines (which can require extensive programming), the only way the user can correct errors is for him to notice the error before he presses Return so that he can backspace and retype his data. Error checking routines range from a simple

INPUT "Do you want to make any changes? (Y/N) "; YN$

followed by more questions and INPUT statements, to complex screen structures with vertical and horizontal tabbing combined with the INPUT statement.

If the program uses formatted displays, then more programming effort may be required to reformat the screen for the display after each INPUT sequence.

Microsoft BASIC for the Macintosh (Version 2.0 or later) has some built-in features that can help you alleviate some, if not all, of these problems. Formatted screen displays can be kept intact by overlaying windows for the input routines. INPUT can be replaced by EDIT FIELD and EDIT$ to provide a powerful error-checking routine that allows the operator to check all of his data before signifying that everything is correct and proceeding to the next task.

Listing 1 contains a routine just for this purpose. The routine is in the form of a subprogram so that it can be inserted anywhere in your program. Sub- programs are, to my knowledge, unique to the Macintosh version of BASIC. They are independent modules that can be anywhere within a program listing and are completely ignored by BASIC unless they are CALLed by the program. All variables used by a subprogram remain with the subprogram and do not affect the variables in the main program unless explicitly allowed to do so by the program. If A = 10 in the main program and a subprogam sets A equal to 136.43, when the subprogram exited, A would still equal 10 in the main program. Pascal programmers will recognize subprograms as being very similar to Pascal's procedures.

The listing has two parts. The first is an example of a main program for the subprogram to work within. The second is the the subprogram itself.

The main program starts by setting all variables as integers. It then DIMensions the arrays label$, info$, and corner. Label$ contains the names of the edit fields; info$ holds the actual information inputted, and corner defines the four corners of the main window. Next, the label$ and corner data are read into their respective arrays and some sample text is printed in the window. The program then CALLs the subprogram, which is named inputroutine. (Note that the keyword “CALL” is optional.) After the subprogram is exited, the main program transfers the data from the general array to individually named variables. It then formats and prints the data and asks whether the user wants to redo the operation and then waits for a key press to end or redo the program.

Fig. 1 Program Output

Look at the line “doitagain” in the main program. This line calls the subroutine. The list following the subprogram's name contains those variables that are passed to the subprogram. If a variable is not in this list, it is not passed to the subprogram. Corner, info$ and label$ each has a pair of parentheses after it. This is to tell BASIC that these elements are array variables.

In addition to passing variables, you can also pass expressions. As an example, if you need to pass the area of a circle to a subprogram called computeit, but computit does not need to know the radius, you can pass the area like this:

CALL computit (3.14159 * radius ^ 2)

Subprograms cannot change the values of expressions passed to it; they can change only the values of variables. If you need to pass a variable and want to make sure that the subprogram will not change its value, place parentheses around the variable and it will be passed as a value by expression.

Now let's look at the subprogram itself. The first line starts with SUB to indicate that it is a subprogram. The next part of the line is the subprogram's name, followed by a variable list in parentheses. The line concludes with the keyword STATIC.

The subprogram next defines the sizes of window 2 and the portion of window 1 that will be hidden by window 2. It continues by dimensioning the rectangle array that will hold the screen behind window 2; then it defines the shape of the text cursor. The next line, which starts with the ketyword GET, stores the about to be covered portion of window 1 in the previously dimensioned rectangle array. Window 2 is then opened, covering a portion of window 1.

Then the subprogram goes to the subroutine “refresh.” This routine clears the window, sets the font to 0 (Chicago), and prints the labels for the edit fields. It then returns to the main part of the sub program. This subroutine is accessed whenever a portion of the window is covered by another window such as the command or a list window.

The subprogram then resets the font to the default font (Geneva) and draws the edit fields and an OK button. When the edit fields are drawn, the latest information generated in those fields are placed into them for editing. This helps when a field remains the same from one record to another. Because the text in each field is selected when the field is first chosen by tabbing to it, putting in new data is not any more difficult than if the field were left blank..

The next line flushes any dialog actions from memory and then allows the program to continue by initializing and entering a WHILE loop. The first block of programming within the loop monitors the cursor position on the screen and whenever the cursor moves into an edit field, changes it to an I-beam to show text insertion. When the cursor moves outside of the edit field, it reverts to the default arrow. If you have fewer than 10 edit fields, you will need to make minor modifications to this portion of the program.

The next block looks for dialog actions. The only dialog events it recognizes are clicking in the OK box or in an edit field, pressing the Return or Tab key, or obscuring the window with another window.

If the window is obscured, the program goes to the refresh subroutine which clears the window and reprints the field labels. Neither the CLS statement nor covering the window affect buttons or edit fields (including their contents), so they do not need to be refreshed.

If the dialgog event shows that the Tab key had been pressed or that the mouse was clicked in an edit field, the program goes to the tabfield subroutine. If the Tab key had been pressed, the routine increments or decrements the current edit field by 1. Note the line “shiftkey = (PEEK (379) and &H1) * 2.” Peeking memory location 379 monitors various keys on the keyboard. If bit 0 is set, that means that the shift key has been pressed. By ANDing location 379 with the value 1, the result is 1 if the shift key has been pressed and is 0 if it has not been pressed. If the TAB key has been pressed, rather than the mouse clicked in the and edit field, the next line subtracts the value shiftkey (which is either 2 or 0) from the value of currentfield + 1. Therefore the value of currentfield is increased by 1 if the TAB key has been pressed and the shift key has not been pressed. But, if both the shift and TAB keys have been pressed, then currentfield is decreased by 1. This allows for reverse tabbing. If the value of currentfield is less than 1 or greater than maxfields, the value is then currentfield is set to maxfields or 1, respectively. If the TAB key had not been pressed, that means that the subroutine was entered because an edit field was selected by a mouse click, and the current field is set to that field. The subroutine then returns to the line that called it.

If Return (or Enter) is pressed or the OK button is clicked, the variable dialogactive is set to false (0) and the WHILE loop ends.

Note that at no time an express INPUT is made to obtain data from the computer operator. All the operator has to do is enter the information in the edit field boxes in any order of his choice. When the WHILE loop is exited by pressing Return or clicking in the OK button, the information stored in the variable array EDIT$() are transferred to the info$() variable array. Note that this transfer of data must be done before window 2 is closed. When the window closes, the information in the edit fields and EDIT$ will be lost. Note that EDIT$ is never explicitly DIMensioned; DIMensioning is automatically done as the edit fields are created.

Before the subprogram exits and returns to the main program, it closes window 2; PUTs the stored screen data back, thereby restoring window 1; and ERASEs the cursor and rect arrays. Erasing the arrays serves two purposes:

1. It enables them to be reinitialized when the subprogram is next called and

2. It frees the memory used by these arrays so the program can use it for other purposes.

The sub program does seem at first glance to be a bit complex and involved to be a substitute for a series of simple INPUT statements. However, if you were to write an input routine to get a set of data and allow complete editing and error checking of that data, it would be more involved than this routine. This subprogam can be simplified if size and memory are a consideration. The first simplification is be to eliminate the block of programming that changes the shape of the cursor. This block starts with the line “dummy = MOUSE (0)” and ends with the line that ends “ELSE INITCURSOR.” You can then delete all lines that refer to or define the cursor array. The second deletion is the subroutine “tabfield.” If you do that, you must also delete the line that starts “IF status = 2” since this line calls the subroutine. If you delete this routine, the operator can move between edit fields only by means of the mouse. Pressing the Tab key would no longer change the edit fields.


After you enter the entire program and try it out, delete the main program and keep only the subprogram. Save the subprogram, choosing the TEXT option in the save window. When you are ready to use it, MERGE it into your program. MERGE works only if the merged program has been saved in TEXT format.

Prior to calling the subprogram, your program must set the variable “maxfields” to the number of fields to be input; the number of edit fields and labels are taken from this number. You need then only put in the names of the labels (in the label$ array) and transfer the information from the info$ array to your specific variables. The only other change you must make is to the cursor shape-changing routine if you haven't deleted it and if maxfields is other than 10. You can call the subprogram from different parts of your program, using appropriate values for maxfields and labels.

Using this subprogram in your programs will give you a clean-looking, efficient, error-free input routine and save you programming time.

Program Listing
maxfields = 10 'number of fields to be inputted

DIM label$ (maxfields), info$ (maxfields), corner (4)
DATA Last Name,First Name,MI,Title,Street and      No.,City,ST,ZIP,Phone,Ref 
#: 'field labels
FOR i = 1 TO maxfields: READ label$(i): NEXT

'Create main window

DATA 10,30,501,310: 'Change numbers to re-size windows
FOR i = 1 TO 4: READ corner (i): NEXT
WINDOW 1,"",(corner (1),corner (2))-(corner (3),corner (4)),2 

PRINT "This is the background window in which      the main program runs."
PRINT "It will be covered by the data input  window and restored when"
PRINT "the data input window is closed."

doitagain: inputroutine corner (), maxfields, label$(), info$()

Lname$ = info$(1):Cname$ = info$(2)
MI$ = info$(3):Pre$ = info$(4)
street$ = info$(5):City$ = info$(6)
ST$ = info$(7):ZIP$ = info$(8)
Phone$ = info$(9):REFNUM$ = info$(10)

'Use VAL function to change strings to numbers where necessary

IF Pre$ <> "" THEN PRINT Pre$;" ";
PRINT Cname$;" ";
IF MI$ <>"" THEN PRINT MI$;". ";
PRINT Lname$
IF street$ <> "" THEN PRINT street$
IF City$ <> "" THEN PRINT City$; ", ";
IF ST$ <> "" THEN PRINT ST$; "  "; ZIP$
IF Phone$ <> "" THEN PRINT Phone$
IF REFNUM$ <> "" THEN PRINT label$(10);" ";REFNUM$
PRINT:PRINT"Press Return to end or press any other key to try it again."

loop: test$ = INKEY$: IF test$ = "" THEN loop      ELSE IF test$ = CHR$(13) 
THEN END  ELSE doitagain

'Subroutine begins here

SUB inputroutine (corner(), maxfields, label$(),   info$()) STATIC
left = 25: top = 50: right = 480: bottom = 300 'window 2 corners; change 
to re-size window
getleft = left - corner (1) -1: gettop = top - corner (2)      - 1: getright 
= right - corner (1): getbottom =  bottom - corner (2) 'corners of rectangle 
for GET
DIM rect(4+(((getbottom-gettop)+1) * 2 * INT       (((getright-getleft) 
+ 16)/16))), cursor (33)

'Create I-beam cursor

FOR i = 3 TO 12: cursor (i) = &H80: NEXT
cursor (0) = &H630: cursor (15) = cursor (0)
cursor (1) = &H140: cursor (14) = cursor (1)
cursor (2) = &H80: cursor (13) = cursor (2)
FOR i = 16 TO 31: cursor (i) = &H0: NEXT
cursor (32) = &HC
cursor (33) = &H9

GET(getleft,gettop)-(getright,getbottom),rect 'Preserve background 

WINDOW 2,"",(left,top)-(right,bottom),3
GOSUB refresh 'Window refresh routine
TEXTFONT 1 'setup edit fields with Geneva font

FOR i = maxfields TO 1 STEP -1

    EDIT FIELD i,info$(i),(30+((i-1) MOD 2)  *220,(i+(i MOD 2))*20-15)-(220+((i-1) 
MOD   2)*220,15+(i+(i MOD 2))*20-15)

BUTTON 1,1,"OK",(10,230)-(445,250)
WHILE DIALOG (0) <> 0: WEND 'flushes dialog queue    
dialogactive = -1
WHILE dialogactive
     'monitor cursor position and switch cursor shape
    dummy = MOUSE (0): hloc = MOUSE (1): vloc = MOUSE (2)
    IF NOT ((hloc > 30 AND hloc <220) OR (hloc     > 250 AND hloc <470)) 

    IF (hloc>30 AND hloc<220) OR (hloc>250   AND hloc<470) THEN IF (vloc>21 
AND   vloc<38) OR (vloc>61 AND vloc<78) OR   (vloc>102 AND vloc<119) 
 OR (vloc>143  AND vloc<160) OR (vloc>183 AND      vloc<200) THEN SETCURSOR 

    status = DIALOG (0)
    IF status =1 OR status = 6 THEN dialogactive = 0 'check for OK button 
or RETURN key
    IF status =2 OR status = 7 THEN  GOSUB   tabfield 'Check for click 
in edit field or for TAB  key
    IF status =2 OR status = 7 THEN  GOSUB tabfield 'Check for click 
in edit field or for TAB key
    IF status = 5 THEN GOSUB refresh
FOR i = 1 TO maxfields: info$(i) = EDIT$(i): NEXT

PUT (getleft,gettop),rect 'restore backgrnd 
ERASE rect, cursor

tabfield: 'selects edit field with TAB key or mouse
    shiftkey = (PEEK (379) AND &H1) * 2

    IF status = 7 THEN currentfield = currentfield +1 
 - shiftkey ELSE currentfield = DIALOG(2)
    IF currentfield < 1 THEN currentfield = maxfields
    IF currentfield > maxfields THEN currentfield=1

    EDIT FIELD currentfield

refresh: 'redraw window contents

    FOR i = 1 TO maxfields
        MOVETO 30+((i-1) MOD 2)*220, (i+(i MOD 2))*20 - 20
        PRINT label$(i);


Community Search:
MacTech Search:

Software Updates via MacUpdate

The beginner's guide to Warbits
Warbits is a turn-based strategy that's clearly inspired by Nintendo's Advance Wars series. Since turn-based strategy games can be kind of tricky to dive into, see below for a few tips to help you in the beginning. Positioning is crucial [Read... | Read more »
How to upgrade your character in Spellsp...
So you’ve mastered the basics of Spellspire. By which I mean you’ve realised it’s all about spelling things in a spire. What next? Well you’re going to need to figure out how to toughen up your character. It’s all well and good being able to spell... | Read more »
5 mash-ups we'd love to...
If there's one thing that has proved, it's that the addictive gameplay of can be transplanted onto basically anything and it will still be good fun. It wouldn't be surprising if we saw other developers jumping on the bandwagon,... | Read more »
How to navigate the terrain in Sky Charm...
Sky Charms is a whimsical match-'em up adventure that uses creative level design to really ramp up the difficulty. [Read more] | Read more »
Victorious Knight (Games)
Victorious Knight 1.3 Device: iOS Universal Category: Games Price: $1.99, Version: 1.3 (iTunes) Description: New challenges awaits you! Experience fresh RPG experience with a unique combat mechanic, packed with high quality 3D... | Read more »
Agent Gumball - Roguelike Spy Game (Gam...
Agent Gumball - Roguelike Spy Game 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: Someone’s been spying on Gumball. What the what?! Two can play at that game! GO UNDERCOVERSneak past enemy... | Read more »
Runaway Toad (Games)
Runaway Toad 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: It ain’t easy bein’ green! Tap, hold, and swipe to help Toad hop to safety in this gorgeous new action game from the creators of... | Read more »
PsyCard (Games)
PsyCard 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: From the makers och Card City Nights, Progress To 100 and Ittle Dew PSYCARD is a minesweeper-like game set in a cozy cyberpunk... | Read more »
Sago Mini Robot Party (Education)
Sago Mini Robot Party 1.0 Device: iOS Universal Category: Education Price: $2.99, Version: 1.0 (iTunes) Description: -- Children's Technology Review Editor's Choice -- | Read more »
Egz – The Origin of the Universe (Games...
Egz – The Origin of the Universe 1.0.2 Device: iOS Universal Category: Games Price: $3.99, Version: 1.0.2 (iTunes) Description: ►►► Special offer until 2nd may : get the game at 2.99€ instead of 3.99€ ! ◄◄◄ Egz is a mesmerizing mix... | Read more »

Price Scanner via

SanDisk Half-Terabyte SSD Optimized for Every...
SanDisk Corporation has announced the SanDisk Z410 SSD, a cost-competitive, half-terabyte solid state drive (SSD) that enables manufacturers to design for a broad range of desktop PCs and laptops.... Read more
Churchill Downs Racetrack Selects VenueNext t...
Churchill Downs Racetrack has announced an agreement with VenueNext to implement its technology platform for the start of Churchill Downs 2016 Spring Meet, which includes the 142nd running of the... Read more
Record 700 Million Pounds of CE Recycled in 2...
The Consumer Technology Association (CTA) reports that a record-setting 700 million pounds of consumer electronics (CE) have been recycled under the eCycling Leadership Initiative (ELI). According to... Read more
Price drops on clearance 12-inch Retina MacBo...
B&H Photo has dropped prices on leftover 2015 12″ Retina MacBooks with models now available starting at $999. Shipping is free, and B&H charges NY tax only: - 12″ 1.1GHz Gray Retina MacBook... Read more
15-inch Retina MacBook Pros available for $20...
B&H Photo has 15″ Retina MacBook Pros on sale for up to $210 off MSRP. Shipping is free, and B&H charges NY tax only: - 15″ 2.2GHz Retina MacBook Pro: $1799 $200 off MSRP - 15″ 2.5GHz Retina... Read more
Target offers Apple Watch Sport for $50 off M...
Target has Apple Watch Sports on sale for $50 off MSRP for a limited time. Choose free shipping or free local store pickup (if available). Sale prices for online orders only, in-store prices may vary... Read more
Apple restocks Certified Refurbished Mac mini...
Apple has restocked Certified Refurbished 2014 Mac minis, with models available starting at $419. Apple’s one-year warranty is included with each mini, and shipping is free: - 1.4GHz Mac mini: $419 $... Read more
15-inch 2.2GHz Retina MacBook Pro on sale for... has the 15″ 2.2GHz Retina MacBook Pro on sale for $1699.99 including free shipping. Their price is $300 off MSRP, and it’s the lowest price available for this model from any reseller (and... Read more
Apple Beats Microsoft at Own Game; Amazon Pri...
First quarter seasonality combined with an overall disinterested customer base led to an annual decline of 14.7% in worldwide tablet shipments during the first quarter of 2016 (1Q16). Worldwide... Read more
Tablets Had Worst Quarter Since 2012, says St...
The global tablet market began 2016 just as 2015 left off, down. Tablet shipments fell 10% to 46.5 million units during the Q1 2016, according to the new “Preliminary Global Tablet Shipments and... Read more

Jobs Board

Restaurant Manager (Neighborhood Captain) - A...
…in every aspect of daily operation. WHY YOU'LL LIKE IT: You'll be the Big Apple . You'll solve problems. You'll get to show your ability to handle the stress and Read more
Simply Mac *Apple* Specialist- Service Repa...
Simply Mac is the largest premier retailer of Apple products in the nation. In order to support our growing customer base, we are currently looking for a driven Read more
*Apple* Retail - Multiple Positions - Apple,...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
Restaurant Manager (Neighborhood Captain) - A...
…in every aspect of daily operation. WHY YOU'LL LIKE IT: You'll be the Big Apple . You'll solve problems. You'll get to show your ability to handle the stress and Read more
Automotive Sales Consultant - Apple Ford Linc...
…you. The best candidates are smart, technologically savvy and are customer focused. Apple Ford Lincoln Apple Valley is different, because: $30,000 annual salary Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.