introduction to true basic

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

Upload: loyangamba-thangjam

Post on 28-Apr-2015

51 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: Introduction to True BASIC

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 statements4. Subprograms, local and shared variables 5. Arrays 6. Input/output7. Graphics 8. String variables 9. Advanced topics10. 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 & TobochnikLET m = 2 ! mass in kilogramsLET a = 4 ! acceleration in mks unitsLET force = m*a ! force in NewtonsPRINT forceEND

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.

Page 2: Introduction to True BASIC

 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 product2INPUT mINPUT prompt "acceleration a (mks units) = ": aLET force = m*a ! force in Newton'sPRINT "force (in Newtons) ="; forceEND

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 structuresTrue BASIC uses a FOR or a DO construct to execute the same statements more than once. An example of a FOR loop follows:

Page 3: Introduction to True BASIC

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 = 0FOR n = 1 to 100 LET sum = sum + 1/(n*n) PRINT n,sumNEXT nEND

 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 structureLET sum = 0LET n = 0LET relative_change = 1 ! choose large valueDO while relative_change > 0.0001 LET n = n + 1 LET newterm = 1/(n*n) LET sum = sum + newterm LET relative_change = newterm/sum

Page 4: Introduction to True BASIC

PRINT n,relative_change,sumLOOPEND

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 statementsThe 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 decision1LET x = 0DO 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,fLOOPEND

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 decision2LET x = 0DO 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 + 1LOOPEND

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. 

Page 5: Introduction to True BASIC

Table 1. Summary of relational operators.relation operator

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

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 decision3LET x = 0DO 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 ! note syntax END IFLOOPEND

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

Page 6: Introduction to True BASIC

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 passedCALL initial(x,y) ! initialize variablesCALL add(x,y,sum) ! add two variablesCALL multiply(x,y,product)PRINT "sum ="; sum, "product ="; productEND ! end of main program

SUB initial(x,y) INPUT x INPUT yEND SUB

SUB add(x,y,sum) LET sum = x + yEND SUB

SUB multiply(x,y,product) LET product = x*yEND 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.)

Page 7: Introduction to True BASIC

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_passLET x = 10 ! local variable name x defined in main programCALL add_onePRINT xEND

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

What are the values of x and y if SUB add_one in Program pass is written in the following form?

PROGRAM passLET x = 10LET y = 3CALL add_one(x)CALL add_one(y)PRINT x,yEND

SUB add_one(s) ! example of the use of dummy arguments LET s = s + 1END SUB

 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 functionDECLARE DEF fLET delta = 0.01 ! incremental increaseLET sigma2 = 1 ! variance LET x = 0 ! initialize variables even though unnecessaryDO PRINT x,f(x,sigma2) LET x = x + deltaLOOP until key inputEND

Page 8: Introduction to True BASIC

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 functionabs(x) absolute valuesqr(x) square rootexp(x) exponential functionlog(x) natural logarithmlog10(x) logarithm base 10sin(x) sine functioncos(x) cosine functiontan(x) tangent functionint(x) integer partmod(x,y) remainder when x is divided by ymax(x,y) larger of x and ymin(x,y) smaller of x and yremainder(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

Page 9: Introduction to True BASIC

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 randomRANDOMIZELET N = 100FOR i = 1 to N LET integer = int(N*rnd) + 1 PRINT integer;NEXT iEND

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. ArraysAn 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 ! illustrate use of arraysDIM a(3),b(3) ! arrays defined in DIM statementCALL 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 LET b(3) = 1END 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

Page 10: Introduction to True BASIC

PRINT "scalar product = "; dot_productEND 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 componentEND 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

Page 11: Introduction to True BASIC

The PRINT statement displays output on the screen. Some simple extensions of the PRINT statement include

PRINT "x","y","z"PRINT x,y,zPRINT ! skip linePRINT "time ="; tPRINT 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 outputIf 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 ! output occupies 8 spaces including decimal pointPRINT using "----.###": t,x,v ! - prints number with leading space or minus signPRINT using "--%%.###": t,x,v ! % 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 inputThe 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_barDO GET KEY k PRINT kLOOP until k = 32 ! pressing space bar exits loopEND

Page 12: Introduction to True BASIC

We have already given an example of the use of the logical expression key input.

MouseThe use of the GET MOUSE statement is illustrated in Program mouse:

PROGRAM mouseDO ! 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 IFLOOPEND

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 presseds = 1 mouse button held down while draggings = 2 mouse button clicked at (x,y)s = 3 mouse button released at (x,y)

FilesThe 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 variableINPUT 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 fileOPEN #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 fileFOR i = 1 to 4 LET x = i*i PRINT #1: x ! print column of dataNEXT iCLOSE #1! channel # irrelevant if only one channel open at a timeOPEN #2: name file$, access inputFOR i = 1 to 4 INPUT #2: y ! print column of data

Page 13: Introduction to True BASIC

PRINT yNEXT i! files automatically closed when program terminatesCLOSE #2 ! not necessary but good practiceEND

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 newPRINT #1: NPRINT #1: L! comma added between inputs on the same line so that file! can be read by True BASICFOR i = 1 to N PRINT #1, using "----.######, ----.######": x(i),y(i)NEXT iCLOSE #1! next illustrate how to read file.OPEN #1: name file$, access inputINPUT #1: NINPUT #1: LFOR 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 statementsOne 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_dataDIM x(6)DATA 4.48,3.06,0.20,2.08,3.88,3.36FOR i = 1 to 6 READ x(i) ! reads input from DATA statementNEXT iEND

7. GraphicsThe 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 AnimationA 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

Page 14: Introduction to True BASIC

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 statementSET WINDOW xmin, xmax, ymin, ymax

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

draws a point at (x,y) in the current window coordinates. The statementPLOT 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 ! plot analytical solutionCALL initial(t,tmax,r,Ts,T0)CALL set_up_window(t,tmax,Ts,T0)CALL show_plot(t,tmax,r,Ts,T0)END

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) CLEAREND 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,ymaxEND SUB

SUB show_plot(t,tmax,r,Ts,T0) DECLARE DEF f ! declare use of external function SET COLOR "red" DO while t <= tmax PLOT t,f(t,r,Ts,T0); ! abbreviation for PLOT LINES LET t = t + 0.1 LOOPEND SUB

DEF f(t,r,Ts,T0) 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.

Page 15: Introduction to True BASIC

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 curvePLOT AREA: 1,1;2,1;2,2 draw filled triangleBOX LINES xmin,xmax,ymin,ymax draw rectangleBOX AREA xmin,xmax,ymin,ymax draw filled rectangleBOX CLEAR xmin,xmax,ymin,ymax erase rectangleBOX CIRCLE xmin,xmax,ymin,ymax draw inscribed circle (or ellipse)ASK MAX COLOR mc mc is number of foreground colorsSET COLOR "red" colors include green, blue, brown, magenta, and whiteCLEAR erase contents of current windowFLOOD 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_circleLET r = 1 ! radius of circleSET WINDOW -r,r,-r,rSET 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 reachedFLOOD 0,0END

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 circleLET r = 1 ! radius of circleCALL compute_aspect_ratio(r,xwin,ywin)SET WINDOW -xwin,xwin,-ywin,ywin

Page 16: Introduction to True BASIC

SET COLOR "blue"BOX CIRCLE -r,r,-r,r ! draw circleEND

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 IFEND 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 numbersCALL initial(#1,#2) ! initialize windowsCALL show(#1)CALL show(#2)END

SUB initial(#1,#2) OPEN #1: screen 0,0.5,0,1 ! left-half of screen SET WINDOW 0,1,0,1 SET COLOR "green" OPEN #2: screen 0.5,1,0,1 ! right-half of screen SET COLOR "red" SET WINDOW 0,1,0,1END SUB

SUB show(#9) WINDOW #9 ! note use of dummy variable FOR i = 1 to 100 PLOT rnd,rnd; NEXT iEND SUB

AnimationTo make animations, we can store screen images as a string variable and display them

Page 17: Introduction to True BASIC

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 animationSET WINDOW 1,10,1,10SET COLOR "red"BOX AREA 1,2,1,2 ! draw shapeBOX KEEP 1,2,1,2 in box$ ! store shape in string variable box$CLEARLET x = 1DO while x < 10 BOX CLEAR x,x+1,5,6 ! erase shape LET x = x + 0.1 BOX SHOW box$ at x,5 ! redraw shape at different location PAUSE 0.01 ! choose delayLOOPEND

Another example of the use of animation is shown in Program pendula.

8. String variablesAs 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 stringLET a$ = " "LET b$ = "good"PRINT b$LET b$ = b$ & a$ & "morning" ! & for concatenationPRINT b$LET c$ = b$[1:4] ! extract substringPRINT c$END

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

Table 4. Useful string handling functions.

notation functionlen(x$) number of characters in x$pos(x$,a$,c) first occurrence of a$ in x$ at or after character number clcase$(x$) convert letters to lower caseucase$(x$) convert letters to upper casetrim$(x$) remove leading and trailing blanks

Page 18: Introduction to True BASIC

ltrim$(x$) remove leading blanksrtrim$(x$) 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 filesLET n = 20FOR 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 #iNEXT iEND

9. Advanced topics

Recursion Global variables Strong typing modules Select case Matrix operations

RecursionA 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 isfactorial(n) = n factorial(n-1)

A program that closely parallels the above definition follows.PROGRAM n!DECLARE DEF fLET n = 11PRINT "n! ="; f(n)END PROGRAM

DEF f(n) IF n <= 0 then LET f = 1 ELSE LET f = n*f(n-1) END IFEND DEF

Global variablesSo 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.

Page 19: Introduction to True BASIC

PROGRAM show_publicPUBLIC L,spin(3,3)CALL initialFOR y = 1 to L FOR x = 1 to L PRINT spin(x,y); NEXT x PRINTNEXT yEND

SUB initial DECLARE PUBLIC L,spin(,) 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 yEND SUB

Strong typingUnlike 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_publicOPTION TYPOPUBLIC L,spin(3,3)LOCAL x,yCALL initialFOR y = 1 to L FOR x = 1 to L PRINT spin(x,y); NEXT x PRINTNEXT yEND

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

Page 20: Introduction to True BASIC

LET spin(x,y) = -1 END IF NEXT x NEXT yEND SUB

ModulesA 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 coolingLIBRARY "common"DECLARE PUBLIC r,t,dt,tmax,nshow,T_coffeeCALL outputLET counter = 0DO 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 IFLOOPDOLOOP until key inputEND

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 ! time LET T_coffee = 82.3 ! initial coffee temperature (C) LET T_room = 17.0 ! room temperature (C) LET r = 0.2 LET dt = 0.01 LET tmax = 1 LET tshow = 0.1 LET 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

Page 21: Introduction to True BASIC

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 caseIf 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) + 1SELECT CASE directionCASE 1 LET x = x + 1CASE 2 LET x = x - 1CASE 3 LET y = y + 1CASE 4 LET y = y - 1CASE else PRINT "error"END SELECT

Matrix operationsTrue 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 arithmeticDIM A(4),B(4),C(4),S(2,2),T(2,2),SI(2,2)MAT A = 1MAT B = 2*AMAT C = A + BMAT PRINT A,B,CLET dot_product = dot(A,B) ! dot product of A and BMAT C = A*B ! matrix productDATA 1,3,4,8

Page 22: Introduction to True BASIC

MAT READ SMAT PRINT C,SMAT T = Trn(S) ! transposed matrixMAT SI = Inv(S) ! inverse matrixMAT PRINT T,SI! check that matrix of most recently inverted matrix is not too smallprint detEND

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 ASK MAX COLOR ASK PIXELS BOX AREABOX CIRCLE BOX CLEAR BOX KEEP BOX LINESBOX SHOW CALL channel number CLEARCLOSE comments concatenation DATADECLARE PUBLIC DIM DRAWDO while DO until END ERASEFLOOD FOR loops FUNCTION GET KEYGET MOUSE GET POINT IF INPUTINPUT prompt int key input LETLOCAL library MAT modOPEN OPTION TYPO PAUSE PICTUREPLOT PLOT LINES PLOT POINTS PRINTPRINT using PROGRAM (header) PUBLIC RANDOMIZEREAD RESET round rndSET CURSOR SET COLOR SET WINDOW sgnstring SUB tab truncateWINDOW

Page 23: Introduction to True BASIC

Please send comments and corrections to Harvey Gould, [email protected].

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.