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

Pocket Arcade Story (Games)
Pocket Arcade Story 1.00 Device: iOS Universal Category: Games Price: $4.99, Version: 1.00 (iTunes) Description: Here comes a new challenger: it's the arcade simulation game you've been waiting for! Build your very own gaming... | Read more »
How to get coins faster in Rodeo Stamped...
There comes a time in a cowboy or cowgirl's life when all the riding and lassoing skills in the world aren't enough. You're going to need some cold, hard cash to keep your sky zoo expanding in Rodeo Stampede. [Read more] | Read more »
How to out-do Cam Newton in Can You Dab?
The thing about dance crazes is that you're never really sure when they've run their course. Take the Dab, for instance. Propelled by its adoption as the touchdown celebration of choice for Carolina Panthers quarterback Cam Newton, the Dab seemed... | Read more »
Artik Games releases Splashy Cats for An...
Splashy Cats had us hooked from the title alone, and when we found out the game was literally just zig-zagging one of our favourite pop-culture references, guised as a playable cat character, down a river – our appetites were whetted to say the... | Read more »
Battle Cars (Games)
Battle Cars 1.1 Device: iOS Universal Category: Games Price: $1.99, Version: 1.1 (iTunes) Description: Welcome to the world of Battle Cars. Battle Cars is a classic arcade top-down racing game with fast mini cars and funny weapons to... | Read more »
How to get started with
One could be forgiven for thinking that there are already plenty of streaming video apps out there. It's just that the App Store charts would insist that you're mistaken. [Read more] | Read more »
Rodeo Stampede: Guide to all Savannah an...
A "gotta catch 'em all" joke seems appropriate here, even though we're talking animals in Rodeo Stampede and not pocket monsters. By now you've probably had plenty of rides, tamed some animals and built yourself a pretty nice zoo | Read more »
Is there cross-platform play in slither....
So you've sunken plenty of hours into crawling around in on your iPhone or iPad. You've got your stories of tragedy and triumph, the times you coiled four snakes at one time balanced out by the others when you had a length of more than... | Read more »
Rodeo Stampede guide to running a better...
In Rodeo Stampede, honing your skills so you can jump from animal to animal and outrun the herd as long as possible is only half the fun. Once you've tamed a few animals, you can bring them home with you. [Read more] | Read more »
VoxSyn (Music)
VoxSyn 1.0 Device: iOS Universal Category: Music Price: $6.99, Version: 1.0 (iTunes) Description: VoxSyn turns your voice into the most flexible vocal sound generator ever. Instantly following even subtle modulations of pitch and... | Read more »

Price Scanner via

MacBook Airs on sale for up to $50-$100 off M...
B&H Photo has 13″ and 11″ MacBook Airs on sale for up to $100 off MSRP. Shipping is free, and B&H charges NY sales tax only: - 11″ 1.6GHz/128GB MacBook Air: $849 $50 off list price - 11″ 1.... Read more
Brexit Vote Result Forecast To Slash UK 2016...
Uncertainty and economic volatility can be expected to increase over the next nine months, as the Brexit and concerns over the future of the EU hit IT investment, say Canalys market analysts, with... Read more
13-inch 256GB MacBook Air on sale for $1149,...
Amazon has the 2016 13″ 1.6GHz/256GB MacBook Air (model MMGG2LL/A) on sale for $1149.99 including free shipping. Their price is also $50 off MSRP. Read more
Haven App Launches New Age Of Wirless 911 Eme...
Haven from RapidSOS represents a transformation in access to emergency services from a phone call solely dependent on voice to a robust data connection for voice, text, medical/demographic data.... Read more
Cu Parachute 1.1 Retirement Success PLanning...
Tucson, Arizona based Indie developer Bradley McCarthy has announce the release of Cu (Copper) Parachute 1.1 for iPhone, iPad, and iPod touch devices — a tool with which users can continuously... Read more
Research and Markets Releases iPhone 6s Plus...
A new analysis report from Dublin-based Research and Markets observes that with the iPhone 6s Plus, Apple introduced a new rear camera module. The new device has similar structure and technology than... Read more
Apple refurbished Retina MacBook Pros availab...
Apple has Certified Refurbished 2015 13″ and 15″ Retina MacBook Pros available for up to $380 off the cost of new models. An Apple one-year warranty is included with each model, and shipping is free... Read more
Apple refurbished 11-inch MacBook Airs availa...
Apple has Certified Refurbished 11″ MacBook Airs (the latest models), available for up to $170 off the cost of new models. An Apple one-year warranty is included with each MacBook, and shipping is... Read more
Apple price trackers, updated continuously
Scan our Apple Price Trackers for the latest information on sales, bundles, and availability on systems from Apple’s authorized internet/catalog resellers. We update the trackers continuously: - 15″... Read more
12-inch 32GB and 128GB WiFi iPad Pros on sale...
B&H Photo has 12″ 32GB & 128GB WiFi iPad Pros on sale for up to $80 off MSRP, each including free shipping. B&H charges sales tax in NY only: - 12″ Space Gray 32GB WiFi iPad Pro: $749 $50... Read more

Jobs Board

*Apple* iPhone 6s and New Products Tester Ne...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
*Apple* iPhone 6s and New Products Tester Ne...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
*Apple* Retail - Multiple Positions, Willow...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
*Apple* iPhone 6s and New Products Tester Ne...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
*Apple* iPhone 6s and New Products Tester Ne...
…we therefore look forward to put out products to quality test for durability. Apple leads the digital music revolution with its iPods and iTunes online store, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.