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);

Apple Inc.
Microsoft Corpora
Google Inc.

MacTech Search:
Community Search:

Software Updates via MacUpdate

Tweetbot 1.5.1 - Popular iOS twitter cli...
Tweetbot is a full-featured OS X Twitter client with a lot of personality. Whether it's the meticulously-crafted interface, sounds and animation, or features like multiple timelines and column views... Read more
Mac DVDRipper Pro 4.1.7 - Copy, backup,...
Mac DVDRipper Pro is the DVD backup solution that lets you protect your DVDs from scratches, save your batteries by reading your movies from your hard disk, manage your collection with just a few... Read more
PDFpenPro 6.2 - Advanced PDF toolkit for...
PDFpenPro allows users to edit PDF's easily. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Create... Read more
PDFpen 6.2 - Edit and annotate PDFs with...
PDFpen allows users to easily edit PDF's. Add text, images and signatures. Fill out PDF forms. Merge or split PDF documents. Reorder and delete pages. Even correct text and edit graphics! Features... Read more
Monolingual 1.5.9 - Remove unwanted OS X...
Monolingual is a program for removing unnecesary language resources from OS X, in order to reclaim several hundred megabytes of disk space. It requires a 64-bit capable Intel-based Mac and at least... Read more
Maya 2015 - Professional 3D modeling and...
Maya is an award-winning software and powerful, integrated 3D modeling, animation, visual effects, and rendering solution. Because Maya is based on an open architecture, all your work can be scripted... Read more
Starcraft II: Wings of Liberty
Download the patch by launching the Starcraft II game and downloading it through the connection within the app. Starcraft II: Wings of Liberty is a strategy game played in real-time. You... Read more
Sibelius 7.5.0 - Music notation solution...
Sibelius is the world's best-selling music notation software for Mac. It is as intuitive to use as a pen, yet so powerful that it does most things in less than the blink of an eye. The demo includes... Read more
Typinator 5.9 - Speedy and reliable text...
Typinator turbo-charges your typing productivity. Type a little. Typinator does the rest. We've all faced projects that require repetitive typing tasks. With Typinator, you can store commonly used... Read more
MYStuff Pro 2.0.16 - Create inventories...
MYStuff Pro is the most flexible way to create detail-rich inventories for your home or small business. Add items to MYStuff by dragging and dropping existing information, uploading new images, or... Read more

Latest Forum Discussions

See All

Have a Special Dead Trigger 2 Easter Bas...
Have a Special Dead Trigger 2 Easter Basket Full of Goodies, Courtesy of Madfinger Games Posted by Rob Rich on April 18th, 2014 [ permalink ] Dead Trigger 2 | Read more »
Zynga Launches Brand New Farmville Exper...
Zynga Launches Brand New Farmville Experience with Farmville 2: Country Escape Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
David. Review
David. Review By Cata Modorcea on April 18th, 2014 Our Rating: :: MINIMALISTIC IN A DIFFERENT WAYUniversal App - Designed for iPhone and iPad David is a minimalistic game wrapped inside of a soothing atmosphere in which the hero... | Read more »
Eyefi Unveils New Eyefi Cloud Service Th...
Eyefi Unveils New Eyefi Cloud Service That Allows Users to Share Media Across Personal Devices Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
Tales from the Dragon Mountain: The Lair...
Tales from the Dragon Mountain: The Lair Review By Jennifer Allen on April 18th, 2014 Our Rating: :: STEADY ADVENTURINGiPad Only App - Designed for the iPad Treading a safe path, Tales from the Dragon Mountain: The Lair is a... | Read more »
Yahoo Updates Flickr App with Advanced E...
Yahoo Updates Flickr App with Advanced Editing Features and More Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
My Incredible Body - A Kid's App to...
My Incredible Body - A Kid's App to Learn about the Human Body 1.1.00 Device: iOS Universal Category: Education Price: $2.99, Version: 1.1.00 (iTunes) Description: Wouldn’t it be cool to look inside yourself and see what was going on... | Read more »
Trials Frontier Review
Trials Frontier Review By Carter Dotson on April 18th, 2014 Our Rating: :: A ROUGH LANDINGUniversal App - Designed for iPhone and iPad Trials Frontier finally brings the famed stunt racing franchise to mobile, but how much does its... | Read more »
Evernote Business Notebook by Moleskin I...
Evernote Business Notebook by Moleskin Introduced – Support Available in Evernote for iOS Posted by Tre Lawrence on April 18th, 2014 [ permalink ] | Read more »
Sparkle Unleashed Review
Sparkle Unleashed Review By Jennifer Allen on April 18th, 2014 Our Rating: :: CLASSY MARBLE FLINGINGUniversal App - Designed for iPhone and iPad It’s a concept we’ve seen before, but Sparkle Unleashed is a solidly enjoyable orb... | Read more »

Price Scanner via

iMacs on sale for up to $160 off MSRP this we...
Best Buy has iMacs on sale for up to $160 off MSRP for a limited time. Choose free home shipping or free instant local store pickup (if available). Prices are valid for online orders only, in-store... Read more
iPad Airs on sale this weekend for up to $100...
Best Buy has WiFi iPad Airs on sale for $50 off MSRP and WiFi + Cellular iPad Airs on sale for $100 off MSRP on their online store for a limited time, with prices now starting at $449. Choose free... Read more
Apple restocks refurbished Mac minis starting...
The Apple Store has restocked Apple Certified Refurbished Mac minis for up to $150 off the cost of new models. Apple’s one-year warranty is included with each mini, and shipping is free: - 2.5GHz Mac... Read more
Hyundai Brings Apple CarPlay To The 2015 Sona...
Hyundai Motor America has announced it will bring Apple CarPlay functionality to the 2015 Sonata. CarPlay is pitched as a smarter, safer and easier way to use iPhone in the car and gives iPhone users... Read more
Updated iPads Coming Sooner Than We Had Thoug...
MacRumors, cites KGI securities analyst Ming Chi Kuo, well-respected as an Apple product prognisticator, saying that Apple will introduce an upgraded iPad Air and iPad mini in 2014/Q3, meaning the... Read more
Toshiba Unveils New High And Low End Laptop M...
Toshiba has announced new laptop models covering both the high-end and low-end of the notebook computer spectrum. Toshiba 4K Ultra HD Laptop Toshiba’s new Satellite P55t features one of the world’s... Read more
Save up to $270 with Apple refurbished 13-inc...
The Apple Store has Apple Certified Refurbished October 2013 13″ Retina MacBook Pros available starting at $1099, with models up to $270 off MSRP. Apple’s one-year warranty is standard, and shipping... Read more
Apple now offering refurbished iPad mini with...
The Apple Store has Certified Refurbished 2nd generation iPad minis with Retina Displays now available starting at $339. Apple’s one-year warranty is included with each model, and shipping is free.... Read more
Microsoft Blinks – Drops Microsoft Office 365...
Microsoft has dropped the annual subscription fee for Microsoft Office 365 Personal – which is needed in order to create and edit documents in Microsoft Office for iPad. However, Apple’s iOS and OS X... Read more
New AVG Vault Apps for iOS and Android Help K...
AVG Technologies N.V. an online security company for 177 million active users, has announced the launch of its latest mobile application, AVG Vault. The free app introduces an innovative user... Read more

Jobs Board

*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Retail - Manager - Holyoke - Apple I...
Job Summary Keeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you’re a master of them all. In the store’s fast-paced, Read more
*Apple* Retail - Manager - Apple (United Sta...
Job SummaryKeeping an Apple Store thriving requires a diverse set of leadership skills, and as a Manager, you're a master of them all. In the store's fast-paced, dynamic Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
*Apple* Retail - Market Leader - Cincinnati...
…challenges of developing individuals, building teams, and affecting growth across Apple Stores. You demonstrate successful leadership ability - focusing on excellence Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.