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

Apple GarageBand 10.1.5 - Complete recor...
The new GarageBand is a whole music creation studio right inside your Mac -- complete with keyboard, synths, orchestral and percussion instruments, presets for guitar and voice, an entirely... Read more
Adobe Audition CC 2017 10.0.2 - Professi...
Audition CC 2017 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous Audition customer). Adobe Audition CC 2017 empowers you to create and... Read more
Adobe After Effects CC 2017 14.1 - Creat...
After Effects CC 2017 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous After Effects customer). The new, more connected After Effects CC... Read more
Adobe Premiere Pro CC 2017 11.0.2 - Digi...
Premiere Pro CC 2017 is available as part of Adobe Creative Cloud for as little as $19.99/month (or $9.99/month if you're a previous Premiere Pro customer). Adobe Premiere Pro CC 2017 lets you edit... Read more
WALTR 2 2.0.9 - $39.95
WALTR 2 helps you wirelessly drag-and-drop any music, ringtones, videos, PDF, and ePub files onto your iPhone, iPad, or iPod without iTunes. It is the second major version of Softorino's critically-... Read more
Yummy FTP Pro 1.11.14 - $14.99 (50% off)
Yummy FTP Pro is an advanced Mac file transfer app which provides a full-featured professional toolkit combined with blazing speeds and impeccable reliability, so whether you want to transfer a few... Read more
ExpanDrive 5.4.4 - Access cloud storage...
ExpanDrive builds cloud storage in every application, acts just like a USB drive plugged into your Mac. With ExpanDrive, you can securely access any remote file server directly from the Finder or... Read more
Dash 3.4.3 - Instant search and offline...
Dash is an API documentation browser and code snippet manager. Dash helps you store snippets of code, as well as instantly search and browse documentation for almost any API you might use (for a full... Read more
Civilization VI 1.0.2 - Next iteration o...
Sid Meier’s Civilization VI is the next entry in the popular Civilization franchise. Originally created by legendary game designer Sid Meier, Civilization is a strategy game in which you attempt to... Read more
TurboTax 2016 - Manage your 2016 U.S. ta...
TurboTax guides you through your tax return step by step, does all the calculations, and checks your return for errors and overlooked deductions. It lets you file your return electronically to get... Read more

Red's Kingdom (Games)
Red's Kingdom 1.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0 (iTunes) Description: Mad King Mac has kidnapped your father and stolen your golden nut! Solve puzzles and battle goons as you explore and battle your... | Read more »
Turbo League Guide: How to tame the cont...
| Read more »
Fire Emblem: Heroes coming to Google Pla...
Nintendo gave us our first look at Fire Emblem: Heroes, the upcoming mobile Fire Emblem game the company hinted at last year. Revealed at the Fire Emblem Direct event held today, the game will condense the series' tactical RPG combat into bite-... | Read more »
ReSlice (Music)
ReSlice 1.0 Device: iOS Universal Category: Music Price: $9.99, Version: 1.0 (iTunes) Description: Audio Slice Machine Slice your audio samples with ReSlice and create flexible musical atoms which can be triggered by MIDI notes or... | Read more »
Stickman Surfer rides in with the tide t...
Stickson is back and this time he's taken up yet another extreme sport - surfing. Stickman Surfer is out this Thursday on both iOS and Android, so if you've been following the other Stickman adventures, you might be interested in picking this one... | Read more »
Z-Exemplar (Games)
Z-Exemplar 1.4 Device: iOS Universal Category: Games Price: $3.99, Version: 1.4 (iTunes) Description: | Read more »
5 dastardly difficult roguelikes like th...
Edmund McMillen's popular roguelike creation The Binding of Isaac: Rebirth has finally crawled onto mobile devices. It's a grotesque dual-stick shooter that tosses you into an endless, procedurally generated basement as you, the pitiable Isaac,... | Read more »
Last week on PocketGamer
Welcome to a weekly feature looking back on the past seven days of coverage on our sister website, PocketGamer. It’s taken a while for 2017 to really get going, at least when it comes to the world of portable gaming. Thank goodness, then, for... | Read more »
ROME: Total War - Barbarian Invasion set...
To the delight of mobile strategy fans, Feral Interactive released ROME: Total War just a few months ago. Now the game's expansion, Barbarian Invasion is marching onto iPads as a standalone release. [Read more] | Read more »
Yuri (Games)
Yuri 1.0 Device: iOS iPhone Category: Games Price: $3.99, Version: 1.0 (iTunes) Description: It's night. Yuri opens his eyes. He wakes up in a strange forest.The small, courageous explorer rides on his bed on casters in this... | Read more »

Price Scanner via

Apple’s Education discount saves up to $300 o...
Purchase a new Mac or iPad using Apple’s Education Store and take up to $300 off MSRP. All teachers, students, and staff of any educational institution qualify for the discount. Shipping is free: -... Read more
4-core 3.7GHz Mac Pro on sale for $2290, save...
Guitar Center has the 3.7GHz 4-core Mac Pro (MD253LL/A) on sale for $2289.97 including free shipping or free local store pickup (if available). Their price is a $710 savings over standard MSRP for... Read more
128GB Apple iPad Air 2, refurbished, availabl...
Apple has Certified Refurbished 128GB iPad Air 2s WiFis available for $419 including free shipping. That’s an $80 savings over standard MSRP for this model. A standard Apple one-year warranty is... Read more
13-inch 2.7GHz Retina MacBook Pro on sale for...
B&H Photo has the 2015 13″ 2.7GHz/128GB Retina Apple MacBook Pro on sale for $100 off MSRP. Shipping is free, and B&H charges NY tax only: - 13″ 2.7GHz/128GB Retina MacBook Pro (MF839LL/A): $... Read more
Laptop Market – Flight To Quality? – The ‘Boo...
Preliminary quarterly PC shipments data released by Gartner Inc. last week reveal an interesting disparity between sales performance of major name PC vendors as opposed to that of less well-known... Read more
IBM and Bell Transform Canadian Enterprise Mo...
IBM and Bell Canada have announced they are joining forces to offer IBM MobileFirst for iOS market-ready enterprise applications for iPad, iPhone or Apple Watch. Bell, Canada’s largest communications... Read more
Otter Products is Closing… For a Day of Givin...
On Thursday, Feb. 9, Otter Products is closing doors to open hearts. In partnership with the OtterCares Foundation, the company is pausing operations for a day so all employees can volunteer with... Read more
15-inch 2.2GHz Retina MacBook Pro on sale for...
Amazon has 2015 15″ 2.2GHz Retina MacBook Pros (MJLQ2LL/A) available for $1799.99 including free shipping. Apple charges $1999 for this model, so Amazon’s price is represents a $200 savings. Read more
Back in stock: Apple refurbished 13-inch Reti...
Apple has Certified Refurbished 2015 13″ Retina MacBook Pros available for up to $360 off original MSRP, starting at $1099. An Apple one-year warranty is included with each model, and shipping is... Read more
CalcTape for macOS 1.2 Adding Machine App for...
schoettler Software has announced CalcTape 1.2, an update to their desktop calculator for macOS. When it comes to adding long columns of numbers, doing complex calculations or playing around with... Read more

Jobs Board

*Apple* & PC Desktop Support Technician...
Apple & PC Desktop Support Technician job in Los Angeles, CA Introduction: We have immediate job openings for several Desktop Support Technicians with one of our Read more
*Apple* Retail - Multiple Positions - Apple,...
SalesSpecialist - Retail Customer Service and SalesTransform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
*Apple* Retail - Multiple Positions (Multi-L...
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* Retail - Multiple Positions - Apple,...
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* & PC Desktop Support Technician...
Apple & PC Desktop Support Technician job in Stamford, CT We have immediate job openings for several Desktop Support Technicians with one of our most well-known Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.