TweetFollow Us on Twitter

Subprograms
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.

HOW TO USE THE PROGRAM

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
DEFINT a-z
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

PRINT
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
CLS
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)

NEXT
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)) 
THEN INITCURSOR

    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 
VARPTR  (cursor (0)) ELSE INITCURSOR

    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
WEND
    
FOR i = 1 TO maxfields: info$(i) = EDIT$(i): NEXT

WINDOW CLOSE 2
PUT (getleft,gettop),rect 'restore backgrnd 
ERASE rect, cursor
EXIT SUB

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
RETURN

refresh: 'redraw window contents
    CLS
    CALL TEXTFONT (0)

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

RETURN
END SUB
 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.