You are on page 1of 23

Introduction to True BASIC The BASIC programming language was developed in 1965 by John G. Kemeny and Thomas E.

Kurtz as a language for introductory courses in computer science. In 1988 they extended the language to make it modular and portable.
1. Introduction 2. Loop structures 3. Conditional statements 4. Subprograms, local and shared variables 5. Arrays 6. Input/output 7. Graphics 8. String variables 9. Advanced topics 10. References and links 11. Index (not done)

1. Introduction
True BASIC, C, Fortran, and Pascal are examples of procedural languages. Procedural languages change the state or memory of the machine by a sequence of statements. True BASIC is similar to F (a subset of Fortran 90) and has excellent graphics capabilities which are hardware independent. True BASIC programs can run without change on computers running the Macintosh, Unix, and Windows operating systems. We will consider version 3.0 (2.7 on the Macintosh) of True BASIC. Version 5 includes the ability to build objects such as buttons, scroll bars, menus, and dialog boxes. However, because we wish to emphasize the similarity between True BASIC and other procedural languages such as C, F, and Java, we do not consider these features.

There is no perfect programming language (or operating system) and users should be flexible and choose the appropriate language to accomplish their goals. Former students who were well grounded in True BASIC have had no trouble learning C, F, and Java quickly. This tutorial is based on the text, Introduction to Computer Simulation Methods, by Harvey Gould and Jan Tobochnik. The features of True BASIC which are common to other procedural languages are emphasized. To illustrate the nature of True BASIC, we first give a program that multiplies two numbers and prints the result:
PROGRAM product ! taken from Chapter 2 of Gould & Tobochnik LET m = 2 ! mass in kilograms LET a = 4 ! acceleration in mks units LET force = m*a ! force in Newtons PRINT force END

The features of True BASIC included in the above program include:

The first statement is an optional PROGRAM header. The inclusion of a program header is good programming style. Comment statements begin with ! and can be included anywhere in the program. PROGRAM, LET, PRINT, and END are keywords (words that are part of the language and cannot be redefined) and are given in upper case. The case is insignificant (unlike C, F, and Java). The DO FORMATcommand converts keywords to upper case. The LET statement causes the expression to the right of the = sign to be evaluated and then causes the result to be assigned to the left of the = sign. (The LET statement reminds us that the meaning of the = symbol is not the same as equals.) It is not necessary to type LET, because the DO FORMAT command automatically inserts LET where appropriate. The LET statement can be omitted if the OPTION NOLET statement is included. True BASIC does not distinguish between integer numerical variables and floating point numerical variables and recognizes only two types of data: numbers and strings (characters). The first character of a variable must be a letter and the last must not be an underscore. The PRINT statement displays output on the screen. The last statement of the program must be END. We next introduce syntax that allows us to enter the desired values of m and a from the keyboard.
PROGRAM product2 INPUT m INPUT prompt "acceleration a (mks units) = ": a LET force = m*a ! force in Newton's PRINT "force (in Newtons) ="; force END

Note the difference between the INPUT and INPUT prompt statements and the simple modification of the PRINT statement. What happens if you replace the semicolon after the expression in the PRINT statement by a comma? Modify the program so that it adds, subtracts, and divides two numbers. 2. Loop structures True BASIC uses a FOR or a DO construct to execute the same statements more than once. An example of a FOR loop follows:

PROGRAM series ! add the first 100 terms of a simple series ! True BASIC automatically initializes variables to zero, ! but other languages might not. LET sum = 0 FOR n = 1 to 100 LET sum = sum + 1/(n*n) PRINT n,sum NEXT n END

The use of the FOR loop structure allows a set of statements to be executed a predetermined number of times. The index or control variable (n in Program series) monitors the number of times the loop has been executed. The FOR statement specifies the first and last value of the index and the amount that the index is incremented each time the NEXT statement is reached. Unless otherwise specified, the index is increased by unity until the index is greater than its last value in which case the program goes to the statement after the NEXT statement. In Program series, the index n assumes the values 1 through 100. True BASIC treats n as an integer variable. The block of statements inside the loop is indented for clarity. Use the DO FORMAT command to indent loops automatically. The order of evaluation follows the mathematical conventions shared by all computer languages. Exponentiations are performed first, followed by multiplications and divisions from left to right. Parentheses should be used whenever the result might be ambiguous to the reader. The parentheses in the statement, LET sum = sum + 1/(n*n), are included for clarity. All unassigned variables are automatically initialized to zero. Because C, F, and Java do not, it is recommended that variables such as sum in Program series be initialized explicitly. In many cases the number of repetitions is not known in advance. An example of a DO loop follows:
PROGRAM series_do ! illustrate use of DO LOOP structure LET sum = 0 LET n = 0 LET relative_change = 1 ! choose large value DO while relative_change > 0.0001 LET n = n + 1 LET newterm = 1/(n*n) LET sum = sum + newterm LET relative_change = newterm/sum PRINT n,relative_change,sum

LOOP END

Note the use of the DO while loop structure to repeat the sum until the specified condition is no longer satisfied. An example of the DO until loop structure is illustrated in Program example_f. 3. Conditional statements The IF statement lets a program branch to different statements depending on the outcome of previous computations. An example of the use of the IF statement follows:
PROGRAM decision1 LET x = 0 DO while x < 20 LET x = x + 1 IF x <= 10 then LET f = 1/x ELSE LET f = 1/(x*x) END IF PRINT x,f LOOP END

The IF construct is a compound statement which begins with IF ... then and ends with END IF. The sequence of statements (a block) inside the IF construct is indented for clarity (done automatically by the DO FORMAT command). An example of the IF statement with two or more branches is given by:
PROGRAM decision2 LET x = 0 DO while x <= 30 IF x = 0 then LET f = 0 ELSEIF x <= 10 then LET f = 1/x ELSEIF x <= 20 then LET f = 1/(x*x) ELSE LET f = 1/(x*x*x) END IF PRINT x,f LET x = x + 1 LOOP END

Any number of ELSEIF statements may be used in an IF structure, and IF statements may be nested. The decisions of an IF structure are based on (logical or Boolean) expressions which are either true or false. A logical expression is formed by comparing two numerical or two string expressions by a relational operator. These operators are given in Table 1.

Table 1. Summary of relational operators.


operator equal = less than < less than or equal <= greater than > greater than or equal >= not equal <> relation

If all the choices in the decision structure are based on the value of a single expression, it is sometimes convenient to use a SELECT CASE structure. Although True BASIC explicitly recognizes only two kinds of variables, numeric and string, it implicitly distinguishes between floating point (real) and integer numeric variables. For example, the variable x in Program decision2 is treated as an integer variable and hence stored with infinite precision; the variable f is treated as a real variable and stored to 14 to 16 decimal places depending on the computer. Arithmetic with numbers represented by integers is exact, but arithmetic operations which involve real numbers is not. For this reason, decision statements should involve comparisons of integer variables rather than floating point variables. C and Fortran 90 support the WHILE statement, but F does not. A program equivalent to Program decision2 is given in the following:
PROGRAM decision3 LET x = 0 DO LET x = x + 1 IF x <= 10 then LET f = 1/x ELSE LET f = 1/(x*x) END IF PRINT x,f IF x = 20 then EXIT DO END IF LOOP END

! note syntax

4. Subprograms and local and shared variables dummy variables functions random number sequences

It is convenient to divide a program into smaller units consisting of a main program and subprograms consisting of subroutines and functions. Subprograms are called from the main program or other subprograms. As an example, the following program adds and multiplies two numbers which are inputed from the keyboard.
PROGRAM tasks ! illustrate use of subroutines ! note how variables are passed CALL initial(x,y) ! initialize variables CALL add(x,y,sum) ! add two variables CALL multiply(x,y,product) PRINT "sum ="; sum, "product ="; product END ! end of main program SUB initial(x,y) INPUT x INPUT y END SUB SUB add(x,y,sum) LET sum = x + y END SUB SUB multiply(x,y,product) LET product = x*y END SUB

Program tasks is an example of a modular program, a program which is divided into separate tasks each of which can be written and tested separately. A complete program contains a main program consisting of a series of calls to subprograms. Subroutines are invoked by the CALL statement. Subroutines and functions are called from the main program or other subprograms. A subroutine is defined by a SUB statement; the end of a subroutine is denoted by END SUB. We use only external subroutines and functions. External program units are defined in any order after the END statement of the main program. A subroutine is a separate program unit with its own local variables, that is, the variables in the main program and in each external subroutine and function are available only to the program subunit. A variable name represents a memory location in the computer. If the same variable name is used in two program units, the name represents two different memory locations. The most common method for subroutines to pass information to the main program and to other subroutines is via arguments in the subroutine calls. In Program tasks the variables x, y, sum, and product are passed in this way. (It is a little misleading to say that variable names are passed to a subroutine. More precisely, the

variable names are not passed, but rather the memory location in the computer is passed. The variable name is simply a label that identifies the memory location.) In Program no_pass the variable name x is used in the main program and in SUB add_one, but is not passed. Convince yourself that the result printed for x in the main program is 10. What is the value of x in SUB add_one?
PROGRAM no_pass LET x = 10 CALL add_one PRINT x END ! local variable name x defined in main program

SUB add_one ! variable name x not passed LET x = x + 1 ! local variable name defined in subroutine END SUB

What are the values of x and y if SUB add_one in Program pass is written in the following form?
PROGRAM pass LET x = 10 LET y = 3 CALL add_one(x) CALL add_one(y) PRINT x,y END SUB add_one(s) LET s = s + 1 END SUB ! example of the use of dummy arguments

The variable name in the subroutine declaration need not match the name used in calling the subroutine. We call the declaration variable name a "dummy variable," because it may not actually be used in the program execution. It is only necessary that the number of variables in the declaration equal the number in the calling of a subroutine. Another way of passing information in True BASIC is discussed later. An example of the use of a function is given in the following:
PROGRAM example_f ! example of use of external function DECLARE DEF f LET delta = 0.01 ! incremental increase LET sigma2 = 1 ! variance LET x = 0 ! initialize variables even though unnecessary DO PRINT x,f(x,sigma2)

LET x = x + delta LOOP until key input END DEF f(x,sigma2) ! define Gaussian function with zero mean and variance sigma2 LET f = (2*pi*sigma2)^(-0.5)*exp(-x*x/(2*sigma2)) END DEF

Note that functions do not change the values of arguments to them. Definitions are not limited to a single line. One way to stop a program is to have the user hit any key as shown by the use of the key input statement in Program example_f. The exponentiation operator is ^. The quantity pi (the area of a circle with unit radius) is predefined. Its use is illustrated in Program example_f. (Strictly speaking, pi is a function which has no arguments and whose value is pi.) True BASIC has many intrinsic (built-in) functions. Some of the more frequently used mathematical functions are given in Table 2. Table 2. Useful mathematical functions.
notation abs(x) sqr(x) exp(x) log(x) log10(x) function absolute value square root exponential function natural logarithm logarithm base 10

sin(x) sine function cos(x) cosine function tan(x) tangent function int(x) integer part mod(x,y) remainder when x is divided by y max(x,y) larger of x and y min(x,y) smaller of x and y remainder(x,y) mod(x,y) - y

If you are uncertain how a particular function works, write a little program to test it. For example, what is the value of mod(10,3)? What about mod(-10,3)? What is the difference between the MOD and the REMAINDER functions? True BASIC includes several useful built-in functions besides pi. One of the most useful ones is rnd which produces a random number that is uniformly distributed between zero and one. The same sequence of random numbers appears each time the program is run unless the function RANDOMIZE is called before the rnd function is used. An example of a program which generates random sequences of integers between 1 and N is given below.
PROGRAM random RANDOMIZE LET N = 100 FOR i = 1 to N LET integer = int(N*rnd) + 1 PRINT integer; NEXT i END

Because the effect of the int function is to round the output of rnd down to its nearest integer, it is necessary to add 1. Although it is a good idea to write your own random number generator using an algorithm that you have tested on the particular problem of interest, it is convenient to use the rnd function when you are debugging a program or if accuracy is not important. 5. Arrays An array variable is a data structure consisting of an ordered set of elements of the same data type. One advantage of arrays is that they allow for the logical grouping of data of the same type, for example the x and y coordinates of a particle. The dimension of an array and the passing of arrays to a subroutine is illustrated in Program vector:
PROGRAM vector DIM a(3),b(3) CALL initial(a(),b()) CALL dot(a(),b()) CALL cross(a(),b()) END SUB initial(a(),b()) LET a(1) = 2 LET a(2) = -3 LET a(3) = -4 LET b(1) = 6 LET b(2) = 5 ! illustrate use of arrays ! arrays defined in DIM statement

LET b(3) = 1 END SUB SUB dot(a(),b()) LET dot_product = 0 FOR i = 1 to 3 LET dot_product = dot_product + a(i)*b(i) NEXT i PRINT "scalar product = "; dot_product END SUB SUB cross(r(),s()) ! arrays can be defined in main program or subroutine ! note use of dummy variables DIM cross_product(3) FOR component = 1 to 3 LET i = mod(component,3) + 1 LET j = mod(i,3) + 1 LET cross_product(component) = r(i)*s(j) - s(i)*r(j) NEXT component PRINT PRINT "three components of the vector product:" PRINT " x "," y "," z " FOR component = 1 to 3 PRINT cross_product(component), NEXT component END SUB

The properties of arrays in True BASIC include: Arrays are defined in a DIM statement and the total number of elements of an array is given in parentheses. The array variables a and b in the main program and the array variables r and s in SUB cross are examples of one-dimensional arrays. The lower and upper limit of each subscript in an array can be specified; the default lower limit is 1. Examples of other limits are DIM r(0 to 2) and DIM s(-3 to 3). A colon may be used instead of TO in the DIM statement, for example, DIM r(0:2) and DIM s(-3:3). The arguments in a DIM statement must be numbers, not variables. An element of an array is specified by its subscript value. Arrays can be passed to a subroutine or a function, with empty parentheses and commas used to indicate the dimension of the array. The same name cannot be used for both an array variable and for another type of variable. Because the address of the first element of the array is passed, rather than the entire array, there is no memory or speed penalty when arrays are passed to a subroutine. True BASIC has many intrinsic matrix operations which are similar to the operations in F.

6. Input/output
SET CURSOR PRINT USING GET KEY GET MOUSE Files READ/DATA statements

The PRINT statement displays output on the screen. Some simple extensions of the PRINT statement include
PRINT PRINT PRINT PRINT PRINT "x","y","z" x,y,z ! skip line "time ="; t tab(7);"time";tab(17);"position";tab(28);"velocity"

True BASIC prints at the current cursor position. The function tab(x) moves the cursor to column x. The cursor may be moved by the SET CURSOR statement
SET CURSOR 10, 20 ! row, column

which moves the cursor to row 10 and column 20. SET CURSOR 1,1 moves the cursor to the upper left corner. Because different computers have different numbers of rows and columns, the statement
ASK SET CURSOR max_row,max_col

sets max_row to the largest row number and max_col to the maximum column number. Formatted output If you need to print output to greater accuracy or in a different format than the default used by True BASIC, use the PRINT using statement.
PRINT using "####.###": t,x,v point PRINT using "----.###": t,x,v sign PRINT using "--%%.###": t,x,v ! output occupies 8 spaces including decimal ! - prints number with leading space or minus ! % prints leading zeroes as '0'

Try various values of t, x, and v to see the nature of the output. For example, try t = 15.5, x = -3.222222, and v = 1. Key input The statement GET KEY k waits until the user presses a key, then converts that key into its corresponding number and then converts this number to the variable k.

PROGRAM space_bar DO GET KEY k PRINT k LOOP until k = 32 END

! pressing space bar exits loop

We have already given an example of the use of the logical expression key input. Mouse The use of the GET MOUSE statement is illustrated in Program mouse:
PROGRAM mouse DO ! return current x and y window coordinates and state of mouse GET MOUSE x,y,s IF s = 1 then PRINT "button down",x,y ELSE IF s = 2 then PRINT "button clicked",x,y ELSE IF s = 3 then PRINT "button released",x,y END IF LOOP END

The variable s is the state of the mouse when the cursor is at position (x,y). The possible values of the status are
s = 0 mouse button not pressed s = 1 mouse button held down while dragging s = 2 mouse button clicked at (x,y) s = 3 mouse button released at (x,y)

Files The following program illustrates how to open a text file, write to the file, close the file, and read the file.
PROGRAM single_column ! save data in a single column ! file$ example of string variable INPUT prompt "name of file for data? ": file$ ! channel number #1 associated with file and can be passed to ! subroutines ! various options may be specified in OPEN statement ! access output: write to file only ! create newold: open file if exists, else create new file OPEN #1: name file$, access output, create newold ! True BASIC does not overwrite data in a text file ! ERASE #1 ! erase contents of file ! RESET #1: end ! allows data to be added to end of file FOR i = 1 to 4 LET x = i*i

PRINT #1: x ! print column of data NEXT i CLOSE #1 ! channel # irrelevant if only one channel open at a time OPEN #2: name file$, access input FOR i = 1 to 4 INPUT #2: y ! print column of data PRINT y NEXT i ! files automatically closed when program terminates CLOSE #2 ! not necessary but good practice END

Program single_column uses a string or character variable for the name of the file. The writing of files with multiple columns is more complicated and is illustrated in the following.
file$ = "config.dat" OPEN #1: name file$,access output,create new PRINT #1: N PRINT #1: L ! comma added between inputs on the same line so that file ! can be read by True BASIC FOR i = 1 to N PRINT #1, using "----.######, ----.######": x(i),y(i) NEXT i CLOSE #1 ! next illustrate how to read file. OPEN #1: name file$, access input INPUT #1: N INPUT #1: L FOR i = 1 to N INPUT #1: x(i),y(i) NEXT i

It is necessary to separate columns by a comma, an annoying feature of True BASIC. There are many variations on the open statement, but the above example is typical. READ/DATA statements One way to incorporate data into a program from a file. Another way to store information within a program is by using the DATA and READ statements as illustrated in Program example_data.
PROGRAM example_data DIM x(6) DATA 4.48,3.06,0.20,2.08,3.88,3.36 FOR i = 1 to 6 READ x(i) ! reads input from DATA statement NEXT i END

7. Graphics The platform independent graphics statements of True BASIC are sufficiently

powerful to do useful animations and visualizations. It is recommended that a separate plotting program be used for making presentation graphs and fits to data.
Core statements Aspect ratio Multiple windows Animation

A graphics screen is covered by a grid of pixels. The number of pixels is hardware dependent. In True BASIC the number of pixels is irrelevant because the mapping of the absolute values of the coordinates to the device coordinates or pixels is done by True BASIC. The first step is to specify the range of coordinates which are to be plotted. The statement
SET WINDOW xmin, xmax, ymin, ymax

determines the minimum and maximum x (horizontal) and y (vertical) coordinates. The statement
PLOT POINTS: x,y;

draws a point at (x,y) in the current window coordinates. The statement


PLOT LINES: x1,y1; x2,y2;

draws a line between (x1,y1) and (x2,y2). Program plot_f uses these statements to draw a set of axes and plot the function T(t) = Ts - (Ts - T0) e-rt.
PROGRAM plot_f CALL initial(t,tmax,r,Ts,T0) CALL set_up_window(t,tmax,Ts,T0) CALL show_plot(t,tmax,r,Ts,T0) END ! plot analytical solution

SUB initial(t,tmax,r,Ts,T0) LET t = 0 LET T0 = 83 ! initial coffee temperature (C) LET Ts = 22 ! room temperature (C) INPUT prompt "cooling constant r = ": r INPUT prompt "duration = ": tmax ! time (minutes) CLEAR END SUB SUB set_up_window(xmin,xmax,ymin,ymax) LET mx = 0.01*(xmax - xmin) ! margin LET my = 0.01*(ymax - ymin) SET WINDOW xmin - mx,xmax + mx,ymin - my,ymax + my ! default background color black on all computers except Macintosh PLOT xmin,ymin; xmax,ymin ! abbreviation for PLOT LINES: PLOT xmin,ymin; xmin,ymax END SUB SUB show_plot(t,tmax,r,Ts,T0) DECLARE DEF f SET COLOR "red" DO while t <= tmax PLOT t,f(t,r,Ts,T0); LET t = t + 0.1 LOOP END SUB DEF f(t,r,Ts,T0) ! declare use of external function ! abbreviation for PLOT LINES

LET f = Ts - (Ts - T0)*exp(-r*t) END DEF

The program uses a separate subroutine to set up the screen and another to plot the function. PLOT x,y; is an abbreviation of PLOT POINT x,y. Program simple_map uses the SET WINDOW, PLOT, BOX LINES and ASK MAX COLOR statements to help visualize the trajectory of a two-dimensional dynamical system. A summary of the some of the important graphics statements is given in Table 3. Table 3. Summary of core True BASIC graphics statements.
SET BACKGROUND COLOR "black" SET WINDOW xmin,xmax,ymin,ymax default window coordinates are 0,1,0,1 PLOT POINTS: x,y abbreviation is PLOT x,y PLOT LINES: x1,y1; x2,y2; PLOT start a new curve PLOT AREA: 1,1;2,1;2,2 draw filled triangle BOX LINES xmin,xmax,ymin,ymax draw rectangle BOX AREA xmin,xmax,ymin,ymax draw filled rectangle BOX CLEAR xmin,xmax,ymin,ymax erase rectangle BOX CIRCLE xmin,xmax,ymin,ymax draw inscribed circle (or ellipse) ASK MAX COLOR mc mc is number of foreground colors SET COLOR "red" colors include green, blue, brown, magenta, and white CLEAR erase contents of current window FLOOD x,y fill enclosed region with current foreground color

Aspect Ratio When is a circle not a circle? Run the following program and find out.
PROGRAM no_circle LET r = 1 ! radius of circle SET WINDOW -r,r,-r,r SET COLOR "blue" BOX CIRCLE -r,r,-r,r ! FLOOD 0,0: start from the point 0,0 and color continuous pixels ! until boundary of region is reached FLOOD 0,0 END

The problem is that few computer screens are square and have the same number of pixels in the horizontal and vertical direction. Moreover, it is possible to define multiple windows whose shape is arbitrary. Sometimes it is essential that a

circle really appear circular on the screen. In this case we must correct for the aspect ratio of the screen as done in the following program.
PROGRAM circle LET r = 1 ! radius of circle CALL compute_aspect_ratio(r,xwin,ywin) SET WINDOW -xwin,xwin,-ywin,ywin SET COLOR "blue" BOX CIRCLE -r,r,-r,r ! draw circle END SUB compute_aspect_ratio(r,x,y) LET m = 0.1*r ! margin LET size = r + m ! px, py: # pixels in horizontal and vertical direction ASK PIXELS px,py IF px > py then LET aspect_ratio = px/py LET x = aspect_ratio*size LET y = size ELSE LET aspect_ratio = py/px LET x = size LET y = aspect_ratio*size END IF END SUB

Note the use of the ASK PIXELS statement. Multiple windows So far we have used the entire screen for the default window. The following program illustrates how to use the OPEN statement to use a portion of the screen, make multiple windows, and choose a particular window. Note that each window has an associated channel number and properties such as its own coordinate system and plot color.
PROGRAM multiple_windows ! note passing of channel numbers CALL initial(#1,#2) ! initialize windows CALL show(#1) CALL show(#2) END SUB initial(#1,#2) OPEN #1: screen 0,0.5,0,1 SET WINDOW 0,1,0,1 SET COLOR "green" OPEN #2: screen 0.5,1,0,1 SET COLOR "red" SET WINDOW 0,1,0,1 END SUB SUB show(#9) WINDOW #9 FOR i = 1 to 100 ! left-half of screen ! right-half of screen

! note use of dummy variable

PLOT rnd,rnd; NEXT i END SUB

Animation To make animations, we can store screen images as a string variable and display them again without the need for additional calculation. The following program illustrates the use of the BOX KEEP, BOX CLEAR, and BOX SHOW statements to create the illustrate the illusion of motion across the screen.
PROGRAM animation SET WINDOW 1,10,1,10 SET COLOR "red" BOX AREA 1,2,1,2 BOX KEEP 1,2,1,2 in box$ CLEAR LET x = 1 DO while x < 10 BOX CLEAR x,x+1,5,6 LET x = x + 0.1 BOX SHOW box$ at x,5 PAUSE 0.01 LOOP END

! draw shape ! store shape in string variable box$

! erase shape ! redraw shape at different location ! choose delay

Another example of the use of animation is shown in Program pendula. 8. String variables As mentioned, True BASIC recognizes only two types of variables, numeric and strings. A string variable may be any combination of characters. String variables end in a dollar sign ($). A string constant is any list of characters enclosed in quotation marks. An example of an assignment of a string variable is
LET file_name$ = "config.dat"

A program illustrating the most common operations on string variables follows:


PROGRAM string LET a$ = " " LET b$ = "good" PRINT b$ LET b$ = b$ & a$ & "morning" PRINT b$ LET c$ = b$[1:4] PRINT c$ END

! & for concatenation ! extract substring

True BASIC has many useful string handling functions, some which are summarized in Table 4. Table 4. Useful string handling functions.

notation function len(x$) number of characters in x$ pos(x$,a$,c) first occurrence of a$ in x$ at or after character number c lcase$(x$) convert letters to lower case ucase$(x$) convert letters to upper case trim$(x$) remove leading and trailing blanks ltrim$(x$) rtrim$(x$) remove leading blanks remove trailing blanks

The function str$ converts a number to a string. The function val converts a string to a number. An example of the use of str$ is given in the following program.
PROGRAM read_file ! open n successive files LET n = 20 FOR i = 1 to n LET si$ = str$(i) LET file_name$ = "config" & si$ & ".dat" OPEN #i: name file_name$, access output, create newold PRINT #i: file_name$ PRINT file_name$ CLOSE #i NEXT i END

9. Advanced topics
Recursion Global variables Strong typing modules Select case Matrix operations

Recursion A simple example of a recursive definition is the factorial function factorial(n) = n! = n(n-1)(n-2) ... 1 A recursive definition of the factorial is factorial(n) = n factorial(n-1) A program that closely parallels the above definition follows.
PROGRAM n! DECLARE DEF f LET n = 11 PRINT "n! ="; f(n) END PROGRAM DEF f(n) IF n <= 0 then LET f = 1 ELSE

LET f = n*f(n-1) END IF END DEF

Global variables So far we have shared information between subprograms by using a parameter list. Another way to share information is by declaring variables to be PUBLIC. An example illustrates its use.
PROGRAM show_public PUBLIC L,spin(3,3) CALL initial FOR y = 1 to L FOR x = 1 to L PRINT spin(x,y); NEXT x PRINT NEXT y END SUB initial DECLARE LET L = FOR y = FOR PUBLIC L,spin(,) 3 1 to L x = 1 to L IF rnd < 0.5 then LET spin(x,y) = 1 ELSE LET spin(x,y) = -1 END IF NEXT x NEXT y END SUB

Strong typing Unlike C, F, and Java, True BASIC does not require variables to be declared before they can be used. The enforced declaration of variables is called strong typing and can be "turned on" in True BASIC by using the OPTION TYPO statement. This statement requires all variables to be declared as either LOCAL, PUBLIC or passed. Public variables are not passed in the arguments of the subroutines.
PROGRAM show_public OPTION TYPO PUBLIC L,spin(3,3) LOCAL x,y CALL initial FOR y = 1 to L FOR x = 1 to L PRINT spin(x,y); NEXT x PRINT NEXT y

END SUB initial DECLARE PUBLIC L,spin(,) LOCAL x,y LET L = 3 FOR y = 1 to L FOR x = 1 to L IF rnd < 0.5 then LET spin(x,y) = 1 ELSE LET spin(x,y) = -1 END IF NEXT x NEXT y END SUB

Modules A module is a library of external subprograms. If you are ready to use a module, you are ready to learn another procedural language such as F which uses modules more effectively. An example of a True BASIC program which uses a module follows.
PROGRAM cool ! numerical solution of Newton's law of cooling LIBRARY "common" DECLARE PUBLIC r,t,dt,tmax,nshow,T_coffee CALL output LET counter = 0 DO IF (t >= tmax) then EXIT DO END IF CALL Euler LET counter = counter + 1 ! number of iterations IF (mod(counter,nshow) = 0) then CALL output END IF LOOP DO LOOP until key input END

The module "common" is in a separate file with the same name. PUBLIC statements determine which variables may be accessed from outside the module. SHARE statements determine the variables that are available to all subprograms within the module, but not outside the module.
MODULE common PUBLIC r,t,dt,tmax,nshow,T_coffee SHARE T_room ! initialize variables LET t = 0.0 LET T_coffee = 82.3 LET T_room = 17.0 ! time ! initial coffee temperature (C) ! room temperature (C)

LET LET LET LET LET

r = 0.2 dt = 0.01 tmax = 1 tshow = 0.1 nshow = int(tshow/dt)

SUB Euler LET change = -r*(T_coffee - T_room)*dt LET T_coffee = T_coffee + change LET t = t + dt END SUB SUB output IF t = 0 then PRINT PRINT "time","T_coffee","T_coffee - T_room" PRINT END IF PRINT t,T_coffee,T_coffee - T_room END SUB END MODULE

Select case If all the choices in the decision structure are based on the value of a single expression, it is sometimes convenient to use a SELECT CASE structure instead of multiple ELSEIF statements. An example of the use of the SELECT CASE structure in the context of a two-dimensional random walk follows:
LET direction = int(4*rnd) + 1 SELECT CASE direction CASE 1 LET x = x + 1 CASE 2 LET x = x - 1 CASE 3 LET y = y + 1 CASE 4 LET y = y - 1 CASE else PRINT "error" END SELECT

Matrix operations True BASIC has many operations which operate on an entire array at once. MAT READ, MAT INPUT, and MAT PRINT have obvious meanings. Arrays in which all the elements are the same may be established as follows:
DIM usave(0:21) MAT usave = 1.0

Matrix arithmetic such as adding matrices and dot products can be done as illustrated in the following program. Add some MAT PRINT statements to check the results.
PROGRAM example_matrix ! illustrate simple matrix arithmetic DIM A(4),B(4),C(4),S(2,2),T(2,2),SI(2,2) MAT A = 1 MAT B = 2*A MAT C = A + B MAT PRINT A,B,C LET dot_product = dot(A,B) ! dot product of A and B MAT C = A*B ! matrix product DATA 1,3,4,8 MAT READ S MAT PRINT C,S MAT T = Trn(S) ! transposed matrix MAT SI = Inv(S) ! inverse matrix MAT PRINT T,SI ! check that matrix of most recently inverted matrix is not too small print det END

True BASIC also allows arrays to be redimensioned in a way similar to the use of the allocate and deallocate statements in Fortran 90. But if you have read this far, you are ready to learn Fortran and C. 10. References and links John G. Kemeny and Thomas E. Kurtz, True BASIC Reference Manual, True BASIC (1990). Harvey Gould and Jan Tobochnik, Introduction to Computer Simulation Methods, second edition, Addison-Wesley (1996).

True BASIC Information Center True BASIC programs (Gould & Tobochnik) Programming links F tutorial

11. Index
abs BOX CIRCLE BOX SHOW CLOSE DECLARE DO while FLOOD ASK MAX COLOR BOX CLEAR CALL comments PUBLIC DO until FOR loops ASK PIXELS BOX KEEP channel number concatenation DIM END FUNCTION BOX AREA BOX LINES CLEAR DATA DRAW ERASE GET KEY

GET MOUSE INPUT prompt LOCAL OPEN PLOT PRINT using READ SET CURSOR string WINDOW

GET POINT int library OPTION TYPO PLOT LINES PROGRAM (header) RESET SET COLOR SUB

IF key input MAT PAUSE PLOT POINTS PUBLIC round SET WINDOW tab

INPUT LET mod PICTURE PRINT RANDOMIZE rnd sgn truncate

Please send comments and corrections to Harvey Gould, hgould@clarku.edu. Corrections made on October 26, 1998 thanks to suggestions made by Matthew J. Moelter, Department of Physics, California Polytechnic State University, San Luis Obispo.
Updated 14 January 2003.

2003 Harvey Gould.

You might also like