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
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.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.
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:
The features of True BASIC included in the above program include: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
We next introduce syntax that allows us to enter the desired values of m and a from the keyboard.
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: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
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
In many cases the number of repetitions is not known in advance. An example of a DO loop follows:
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 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
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.| relation | operator |
|---|---|
| equal | = |
| less than | < |
| less than or equal | <= |
| greater than | > |
| greater than or equal | >= |
| not equal | <> |
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 ! note syntax
END IF
LOOP
END
4. Subprograms and local and shared variables
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
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 ! local variable name x defined in main program
CALL add_one
PRINT x
END
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) ! example of the use of dummy arguments
LET s = s + 1
END SUB
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.True BASIC has many intrinsic (built-in) functions. Some of the more frequently used mathematical functions are given in Table 2.
| notation | function |
|---|---|
| abs(x) | absolute value |
| sqr(x) | square root |
| exp(x) | exponential function |
| log(x) | natural logarithm |
| log10(x) | 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 |
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. 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 arrays
DIM a(3),b(3) ! arrays defined in DIM statement
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
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:6. Input/output
| SET CURSOR | PRINT USING | GET KEY | GET MOUSE | Files | READ/DATA statements |
PRINT "x","y","z" PRINT x,y,z PRINT ! skip line PRINT "time ="; t PRINT tab(7);"time";tab(17);"position";tab(28);"velocity"
which moves the cursor to row 10 and column 20. SET CURSOR 1,1 moves the cursor to the upper left corner.SET CURSOR 10, 20 ! row, column
sets max_row to the largest row number and max_col to the maximum column number.Formatted outputASK SET CURSOR max_row,max_col
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.
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 inputPRINT using "####.###": t,x,v ! output occupies 8 spaces including decimal point PRINT using "----.###": t,x,v ! - prints number with leading space or minus sign PRINT using "--%%.###": t,x,v ! % prints leading zeroes as '0'
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.
We have already given an example of the use of the logical expression key input.MousePROGRAM space_bar DO GET KEY k PRINT k LOOP until k = 32 ! pressing space bar exits loop END
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) |
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.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 statementsfile$ = "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
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. 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 | Animation |
determines the minimum and maximum x (horizontal) and y (vertical) coordinates. The statementSET WINDOW xmin, xmax, ymin, ymax
draws a point at (x,y) in the current window coordinates. The statementPLOT POINTS: x,y;
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.PLOT LINES: x1,y1; x2,y2;
PROGRAM plot_f ! plot analytical solution
CALL 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)
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 ! 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
LOOP
END 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.| 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 | |
When is a circle not a circle? Run the following program and find out.
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 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
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 windowsSo 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 ! 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,1
END SUB
SUB show(#9)
WINDOW #9 ! note use of dummy variable
FOR i = 1 to 100
PLOT rnd,rnd;
NEXT i
END SUB
AnimationTo 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.
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 isPROGRAM animation SET WINDOW 1,10,1,10 SET COLOR "red" BOX AREA 1,2,1,2 ! draw shape BOX KEEP 1,2,1,2 in box$ ! store shape in string variable box$ CLEAR LET x = 1 DO 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 delay LOOP END
A program illustrating the most common operations on string variables follows:LET file_name$ = "config.dat"
True BASIC has many useful string handling functions, some which are summarized in Table 4.PROGRAM string LET a$ = " " LET b$ = "good" PRINT b$ LET b$ = b$ & a$ & "morning" ! & for concatenation PRINT b$ LET c$ = b$[1:4] ! extract substring PRINT c$ END
| 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$) | remove leading blanks |
| rtrim$(x$) | remove trailing blanks |
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 |
A simple example of a recursive definition is the factorial function
A recursive definition of the factorial isfactorial(n) = n! = n(n-1)(n-2) ... 1
A program that closely parallels the above definition follows.factorial(n) = n factorial(n-1)
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 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.
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 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 y
END 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_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
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 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 ! 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
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) + 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 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:
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.DIM usave(0:21) MAT usave = 1.0
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.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
0 comments:
Post a Comment