Вы находитесь на странице: 1из 62

1.

Manipulation of BASIC
1.1 Manipulation of BASIC system
1.1.1 Installation of Decimal BASIC

Download BASIC744En.zip (or later) from Decimal BASIC main page ,then
open it and copy the BASICw32 folder to a regular folder or the drive where
you want to install Decimal BASIC.

1.1.2 Starting BASIC

To start BASIC, open the folder where you put the system of decimal BASIC
with an Explorer and double-click BASIC.EXE or .
Windows may display a Security Warning. If so, select 'Run'.

1.1.3 Using Help

If a vacuous help window as shown below appears when you click the help
icon or the help menu, exit BASIC and follow the procedure mentioned below.
Open the folder where Decimal BASIC has been installed, double-click
BASIC.chm .
Then the following dialog appears. Remove the check on "Always ask before
opening this file", and then click "Open".
Then close the help and re-start BASIC.

1.2 Execution of a program


1.1.1 Execution of sample programs

Decimal BASIC is provided with many sample programs. Try to read and
execute them. Click to read in a program from the file.
Click to execute.
Some programs take time for executing. To abort a program, click .

Recommended:
ABS.BASINT.BASMOD.BASSQR.BASTAN.BAS on FUNCTION folder,
PRINT.BASPLOTPOIN.BASPLOTLINE.BAS on STATEMEN folder.
Warning:
Programs included in the Textfile folder generate files. Do not execute before you
understand the meaning of the programs.

1.1.2 Input and Execution of a program

When BASIC is started, program input is ready.


The keyword 'END' is already input.
Enter a program and push the F9 key to run.

1.1.3 Finishing BASIC

Select 'Exit' from the File menu to finish BASIC.

Next
Back

2 Calculations in BASIC
2.1 Variables and numeric expressions
2.1.1 Numeric expressions

Four operations (addition, subtraction, multiplication and division) are


expressed by +, -, *, / , respectively. An exponentiation ab is expressed
by a^b using a circumflex accent, or a caret(^). For example, 2 3 is expressed as
2^3.
When an expression includes different operations, exponentiations are executed
first, multiplications and divisions are executed next, and then additions and
subtractions are executed. Operations of same priority are executed in order
from left to right.

PRINT statement is used to display the result of a calculation.


10 PRINT 2+3*4^2
20 PRINT 3/4*5
30 PRINT 2^4^5
40 END

Line 10 is to calculate 2+342.


Line 20 is to calculate 345. (Note that multiplication and division have same
priority.)
Line 30 is to calculate (24)5. (Note that exponentiations are executed in order
from left to right.)

2.1.2 Parenthesis

To change the priority of operations, you can use parentheses. Double, triple,
parentheses are permitted, but only round brackets '(' and ')' are used.
When a term starting with a negative sign is written in an expression, it must be
parenthesized.

10 PRINT ((2+3)*4)^2
20 PRINT 3*(-4)
30 END

Line 10 is to calculate {(23)4}2.


Line 20 is to calculate 3(-4).

2.1.3 Line Numbers

The number at the left end of each line of the program is called the line number.
Line numbers can be omitted on Decimal BASIC. In this article, line numbers
are written for the purpose of maintaining consistency with the standard, but it
is advisable to omit line numbers when you prepare programs using Decimal
BASIC.

2.1.4 Variables

A storage location of a value in the computer is called a variable. Variables are


named A, B, C, and so on. Long variable name, such as LEFT or RIGHT also
can be used. For the details of naming rule, see the standard.
Either uppercase letters or lowercase letters can be used, but the differences in
case are ignored. For example, both 'A' and 'a' stand for the same variable.

Storing a numerical value into a variable is called assignment. If a new


numerical value is stored into a variable, numerical values held before will
cease to exist and cannot be referred to.
A LET statement is used to assign a numerical value to a variable.
10 LET X=10
20 PRINT 2*X^2+3*X+4
30 END

If a variable name is used in an expression as shown above, the variable name


indicates the numerical value stored in the variable.
The LET statement is written in the form as follows:
LET variable_name = numerical_expression
When a LET statement is executed, the right-hand value is calculated and
substituted for the variable written on the left-hand.

[Note]
The symbol of multiplication cannot be omitted on BASIC. Even if 'xy' is
written intending x*y, 'xy' is interpreted as one variable different from x or y.

Question 1. If the following program is executed, what is the result?


10 LET A=10
20 LET A=A+1
30 PRINT A
40 END

Decimal BASIC has capability of step execution.


Click to start the program in the mode of executing one line at a time.
On the dialog in the figure below, one line is executed at every time the Enter
key is pressed or the OK button is clicked.
In the Debug window, the statement to be executed and the value of each
variable are displayed. Every time one line is executed, watch how the value of
the variable changes.
If you click the arrow at the lower part of the Debug window, you can see the
history retrospectively.

2.1.5 INPUT statement

Use an INPUT statement to assign a value to a variable during execution.


The variables that shall be input on execution are written punctuated by
commas following INPUT.

The following program finds the product of 2 input numbers.


10 INPUT A,B
20 PRINT A*B
30 END

When this program is executed, the dialog as shown in the figure will be
displayed. Type 2 numbers punctuated by a comma and then press the Enter
key.

2.1.6 Large Numbers and Small Numbers


When the following has been executed,
10 PRINT 1/7
20 END

the following is displayed.


.142857142857143

If the absolute value of a calculation result is smaller than 1, it is displayed


omitting a zero preceding the decimal point.
Furthermore, after the execution of the following,
10 PRINT 2^100,2^(-100)
20 END

the following shall be displayed.


1.26765060022823E30 7.88860905221012E-31

These stand for 1.2676506002282310307.8886090522101210-31,


respectively.

2.2 PRINT statement


2.2.1 Character String

A character string can be displayed using a PRINT statement.


A character string is written enclosed with quotation marks.
10 PRINT "ABC"
20 END

If Line 10 is PRINT ABC, it means that the value of a numerical variable ABC
is displayed.

2.2.2 Item delimiters (comma and semicolon)

When calculation result is output, the format can be controlled in the PRINT
statement.

Multiple items can be written in a PRINT statement by delimiting with commas


or semicolons.
If a semicolon is used as an item delimiter, the items are displayed closely. If a
comma is used for an item delimiter, the items are output from a certain column
by outputting extra space characters.
For example, if the following is executed:
10 PRINT 3; 3^2, 1/3, 2*3
20 END

the display is made as follows.


3 9 .333333333333333 6
An ordinary PRINT statement makes a line break at the last. If you want not to
make a line break, write a comma or a semicolon at the tail of the PRINT
statement.
For example,
10 PRINT 1;2;3;
20 PRINT 4;5
30 END

yields the following result.


1 2 3 4 5

A PRINT statement with no output items only makes a line break.


For example,
10 PRINT 1/3
20 PRINT
30 PRINT 3^2
40 END

yields the following.


.333333333333333

2.3 FORNEXT
2.3.1 FORNEXT block

FORNEXT is a repetitive structure, which is often used in application


programs of BASIC. FOR and NEXT are keywords always used as a pair.
A FORNEXT block repeatedly executes the lines put between the FOR line
and the NEXT line while successively changing the value of the variable
specified in the FOR statement.

The program shown below calculates n2 for n=1,2,3,10.

Example 1.
10 FOR n=1 TO 10
20 PRINT n,n^2
30 NEXT n
40 END

On Example 1, line 20 is executed for n=1 first and then line 20 is executed for
n=2. Then line 20 is executed for n=3. The same thing is sequentially repeated,
and finally line 20 is executed for n=10.
Select the step execution and try to check how the value of variable changes
and execution sequence.

To investigate the characteristic of FORNEXT in detail, try to execute the


following program.

Example 2.
10 INPUT n
20 FOR k=1 TO n
30 PRINT k
40 NEXT k
50 PRINT "Last",k
60 END

If you execute this program and enter 10 for n, you will see that the value of k
becomes 11 when the PRINT statement of line 50 is executed. In the above
program, 1 is substituted for k first, and each time the NEXT statement is
executed, 1 is added for the value of k, and when it becomes larger than n, the
repetition finishes and the control proceeds to the next line of the NEXT
statement.
And now, what happens if 0 is entered for n? In this case, line 30 is not
executed and only line 50 is executed. The value of k in this example is 1. In
this case, since the value of k is larger than n from the beginning, the control
proceeds to line 50 without executing line 30 and the NEXT statement. This
characteristic is important and should be remembered.

2.3.2 Applications of FORNEXT (the sum or product of a sequence

On the following program, 122232n2 is calculated when a natural


number n is entered through the keyboard.

Example 3
10 INPUT n
20 LET S=0
30 FOR k=1 TO n
40 LET S=S+k^2
50 NEXT k
60 PRINT S
70 END

The sum is calculated using variable S. First, 0 is substituted for S in line 20,
and then k2 is added to S for k=1,2,3,,n in lines 30 to 50.
The same method can be used for calculating the product of a sequence. The
number of permutations nPr (=n(n-1)(n-2)(n-r+1)) can be calculated as
follows:
Example 4.
10 INPUT n,r
20 LET p=1
30 FOR k=(n-r+1) TO n
40 LET p=p*k
50 NEXT k
60 PRINT p
70 END

[Note] The initial value of a variable is 0 in Decimal BASIC, but the standard
does not provide so. In order to make a compatible program, line 20 cannot be
omitted in Example 3.

2.3.3 Applications of FORNEXT sequence defined in recurrence


equations

Use the method of successively updating the values of a variable, and you can
calculate the sequence defined in a recurrence equation.
The following program calculates the n-th term of a sequence {a n} defined by
a1=5an+1=3an+2.
Example 5.
10 INPUT n
20 LET a=5
30 FOR k=2 TO n
40 LET a=3*a+2
50 NEXT k
60 PRINT a
70 END

With this program, the correct answer can be obtained even in the case of n=1.
This is because the value of k exceeds n when 2 is substituted for k and line 40
is not executed at all.

2.3.4 STEP

In a FORNEXT block, the numerical value added to the control variable each
time can be made other than 1.
In the following program, x2 is calculated while adding the value of x in units
of 0.1 from 0 to 1.
Example 6.
10 FOR x=0 TO 1 STEP 0.1
20 PRINT x,x^2
30 NEXT x
40 END

This syntax can be used for the purpose of changing the numerical value from a
large value to a small value.

Example 7.
10 FOR k=10 TO 1 STEP -1
20 PRINT k
30 NEXT k
40 END

Question 2.
In the following program, it seems that the input of an even number for n is
assumed, but an odd number can also be entered. How does it operate?
10 INPUT n
20 FOR k=0 TO n STEP 2
30 PRINT k
40 NEXT k
50 END

2.4 DEF statement


Lets make a table of function values using the capability of FORNEXT.
With the following program, the function value is calculated by changing the
value of x in units of 0.1 from 4 to 4 for the function f ( x ) = x3 -3x +1.
Example 8.
10 DEF f(x)=x^3-3*x+1
20 FOR x=-4 TO 4 STEP 0.1
30 PRINT x,f(x)
40 NEXT x
50 END

If this program is executed, the results are displayed as shown in the figure, and
the entire output can be seen by operating the scroll bar at the right end with the
mouse.
The DEF statement of line 10 is an instruction to define the function. The rule
of naming a function is the same as for a variable. But no identical name can be
used for a function name and a variable name. In line 10, f is used as the
function name. The function name is followed by parentheses and a variable is
written in the parentheses. Following the equal sign, the formula to calculate is
written using the variable written in the parentheses. The variable written in the
parentheses on the left side is different from the variable used in other part of
the program (that is, the storage location of the numerical value is different).

2.5 Supplied Functions (Built-in Functions)


2.5.1 Square roots and absolute values

In BASIC, is written as SQR(x). The absolute value |x| of x is expressed by


ABS(x).
[Note] SQR and ABS are abbreviations of SQuare Root and ABSolute,
respectively.

The length of the hypotenuse of a right triangle with sides of


length a and b is .
The program to enter a and b and find is as follows:
Example 9.
10 INPUT a,b
20 PRINT SQR(a^2+b^2)
30 END

2.5.2 Trigonometric functions


The sine, cosine, and tangent of x can be found using SIN(x), COS(x) and
TAN(x), respectively.
The unit of measuring angle is radian as default, but it is possible to change the
angle measure to degrees by writing
OPTION ANGLE DEGREES
in the beginning of the program.
The following program finds the length of the rest side of a triangle using the
cosine law, when the lengths of two sides a and b and the measure of the
inclued angle C are entered.
Example 10.
10 OPTION ANGLE DEGREES
20 INPUT a,b,C
30 PRINT SQR(a^2+b^2-2*a*b*COS(C))
40 END

2.5.3 Inverse trigonometric functions

Since the formula of the cosine law can be solved for cos A as

the measure of the angle A can be found, given the lengths a,b,c of three sides
of a triangle ABC.
To find the corresponding A from the value of cos A, the built-in function
ACOS(x) of BASIC can be used.
ACOS(x) is a built-in function to find t to become cos t= x in the range of
0t180.

Example 11.
A program to find A by entering a,b,c.
10 OPTION ANGLE DEGREES
20 INPUT a,b,c
30 PRINT ACOS((b^2+c^2-a^2)/(2*b*c))
40 END

The following shows the execution result when a=7, b=3, and c=5 are entered.
? 7,3,5
120

As similar built-in functions, ASIN(x), ATN(x) and ANGLE(x,y) are available.

ASIN(x) finds t such that sin t = x and -90t90.

ATN(x) finds t such that tan t = x and -90t90.


ANGLE(x,y) finds the angle between the positive x-axis and the vector joining
the origin and the point (x, y) in the range of -180t180.

2.5.4 INT function and MOD function

INT(x) is the largest integer not exceeding x. If n is an integer, INT(n) agrees


with n, but if it has a fraction part, it is truncated in the negative direction. For
example, INT(2.3)=2, INT(2.3)=3.

MOD(a,b) is a remainder when a is divided by b. It is defined by MOD(a,b)=a


b*INT(a/b). For example, MOD(5,3)=2, MOD(4,3)=2, MOD(1.3,
0.4)=0.1. For a positive number b, 0MOD(a,b)<="" p="">

2.5.5 PI function and so on

IN BASIC, some built-in functions are prepared to stand for special constants.
PI is the approximate value of the ratio of the circumference of a circle to its
diameter ().
MAXNUM is the largest number that can be handled with BASIC.

Example 12.
10 PRINT PI, MAXNUM
20 END

2.5.6 Random NumbersRND function

RND is a special function. This function has no parameter, but each time a
calculation is made, a different value is returned. For example, try to execute
the following program.

Example 13
10 FOR k=1 TO 10
20 PRINT RND
30 NEXT k
40 END

The numerical value returned by the RND function is known as the random
number. The RND function generates random values without bias in the range
of 0 to less than 1. The above program returns the same result each time the
execution is made. If you want the random number of a different series each
time the execution is made, execute the RANDOMIZE statement before
executing the RND function as shown below.
To use the RND function in place of a die, do as follows. With this program,
integers of 1 to 6 are obtained by multiplying the value of RND by 6, adding 1,
and taking out the integer part.
10 RANDOMIZE
20 FOR n=1 TO 20
30 PRINT INT(RND*6+1)
40 NEXT n
50 END

2.6 Graphics
2.6.1 Graphs of functions

Use graphics to draw a graph of a function.

Example 14
A program that draws the graph of the function y=x3-3x+1 in the range of
-4x4 and -4y4.
10 DEF f(x)=x^3-3*x+1
20 SET WINDOW -4,4,-4,4
30 DRAW GRID
40 FOR x=-4 TO 4 STEP 0.1
50 PLOT LINES: x,f(x);
60 NEXT x
70 END

After the execution of the program above, the figure show below is obtained.
When the mouse cursor is moved on the window, the coordinates of the point
are displayed at the bottom.
The shape of the drawing pane is square. The number of pixels is determined
adequately from the size of the screen by BASIC system, but you can select
another pixel size in the menu.

The SET WINDOW statement at line 20 sets the coordinate system in the
drawing area such that the range of x coordinates is from 4 to 4, and the
range of y coordinates is from 4 to 4.
The DRAW statement at line 30 draws a grid. This feature is not specified in
the standard, but the same function can be realized by assembling the
instruction specified in the standard.
The PLOT LINES statement at line 50 is used to draw a graph of the function
by drawing line segments to connect points (x, x3-3x+1) successively.
Generally, when PLOT LINES: x,y; is written, the points indicated by this
statement and the PLOT LINES statement to be executed next shall be
connected with a line segment.

2.6.2 SET WINDOW


SET WINDOW x1 , x2 , y1 , y2

sets the coordinate system with the left end x1, right end x2, bottom end y1 and
top end y2.
When a geometric figure is drawn, x2x1=y2y1 is normally required, but in
the case of the function graph in which the vertical axis and horizontal axis
express amounts different in property, it is not required.
For example, the graph of a sine function with the degree measure is drawn as
follows:
Example 15
10 OPTION ANGLE DEGREES
20 DEF f(x)=sin(x)
30 SET WINDOW -360,360,-4,4
40 DRAW GRID(90,1)
50 FOR x=-360 TO 360
60 PLOT LINES: x,f(x);
70 NEXT x
80 END

OPTION ANGLE DEGREES at line 10 must be written before the lines where
SIN(x) functions are written. The grid(a,b) used in line 40 is a grid of
horizontal gaps a, vertical gaps b.

2.6.3 PLOT LINES

PLOT LINES is a statement to draw a polygonal line by connecting specified


points with line segments. The points are specified by delimiting the x
coordinates and y coordinates with a comma (,). It is also possible to specify
multiple points for one PLOT LINES statement. In such a case, the points are
delimited with a semicolon. It is also possible to write a semicolon at the end of
the point list.
If the PLOT LINES statement executed just before ends with a semicolon, the
point specified last by the PLOT LINES executed just before and the point
specified first are also connected with a line segment.

For example, if PLOT LINES: x1, y1, x2, y2 is executed when the PLOT LINES
statement has not been executed yet or the PLOT LINES executed just before
does not end with a semicolon, a line segment connecting two points (x1, y1)
and (x2, y2) is drawn.
This can also be written by dividing into 2 statements like below.
PLOT LINES: x1 , y1 ;
PLOT LINES: x2 , y2

For the PLOT LINES statement, A special form of PLOT LINES statement,
which has no point list, is available. When the PLOT LINES statement
executed just before ends with a semicolon, PLOT LINES statement with no
point list is used to cancel the effect.
For example, it is used when two function graphs are drawn successively as in
the following program.

Example 16.
100 DEF f(x)=x^2
110 DEF g(x)=x^3
120 SET WINDOW -4,4,-4,4
130 DRAW GRID
140 FOR x=-4 TO 4 STEP 0.1
150 PLOT LINES: x,f(x);
160 NEXT x
170 PLOT LINES
180 FOR x=-4 TO 4 STEP 0.1
190 PLOT LINES: x,g(x);
200 NEXT x
210 END

If the above program lacks line 170, the two points (4,f(40)) and (4, g(4))
shall be connected with a line segment.
2.6.4 Parametric Curve

It is easy to draw a curve with parametric equations. The following program


draws a curve x=3cos t y=2sin t.

Example 17.
10 OPTION ANGLE DEGREES
20 DEF f(t)=3*COS(t)
30 DEF g(t)=2*SIN(t)
40 SET WINDOW -4,4,-4,4
50 DRAW grid
60 FOR t=0 TO 360
70 PLOT LINES: f(t),g(t);
80 NEXT t
90 END

2.6.5 Curves in Polar Coordinates

A polar equation r=f() can be converted to a parametric form by means


of x=f() cos, y=f()sin. The following program draws a rose
curve r=sin2.

Example 18.
10 DEF f(t)=SIN(2*t)
20 SET WINDOW -1,1,-1,1
30 DRAW grid
40 FOR t=0 TO 2*PI STEP PI/360
50 PLOT LINES: f(t)*COS(t), f(t)*SIN(t);
60 NEXT t
70 END

2.6.6 Polar Coordinates

It is easy to convert the rectangular coordinates to the polar coordinates in


BASIC.
The rectangular coordinates (x, y) can be converted to polar coordinates (r, )
by r=SQR(x^2+y^2), =ANGLE(x,y). Provided .
The following program draws a locus of the point where the length of the
radius vector of point P moving on a circle x=1+cos t, y=sin t is squared and
the polar angle is doubled.
Example 19.
100 SET WINDOW -4,4,-4,4
110 DRAW grid
120 FOR t=0 TO 2*pi STEP pi/180
130 LET x=cos(t)+1
140 LET y=sin(t)
150 LET r=x^2+y^2
160 LET a=ANGLE(x,y)*2
170 PLOT LINES: r*cos(a),r*sin(a);
180 NEXT t
190 END

2.6.7 SET LINE COLOR


When multiple curves are drawn on the same plane of coordinates, it may be
desired to change the color for each curve. The instruction to change the color
of a line is SET LINE COLOR. The color is specified by number. On Decimal
BASIC, colors are assigned to numbers as follows:
0 white, 1 black, 2 blue, 3 green, 4 red, 5 cyan, 6 yellow, 7 magenta, 8 gray, 9
navy, 10 dark green, 11 teal, 12 maroon, 13 olive, 14 purple, , 15 silver, .
For example, If SET LINE COLOR 4 is executed, subsequent lines are drawn in
red.

2.6.8 PLOT POINTS

When it is desired to draw a point, the shape of the point is specified by


executing SET POINT STYLE. The shape of a point is specified using one of
the following numbers. If it is not specified, the shape of No. 3 is used.
1 2 + 3 4 5

The color of the point can be changed with SET POINT COLOR. The
instruction to dot a point is PLOT POINTS. It is written in the following form.
PLOT POINTS: x,y

2.7 Numerical Calculation


2.7.1 Square Root

We consider a method of finding an approximate value of the square root of a


positive number using only the four operations.
is the length of one side of a square whose area is the same as that of a
rectangle with length a and width 1 .
If the original rectangle is deformed with its area remaining in such a way that
the width and the length approach each other, the length of this rectangle
should approach . We adopt the average of the length and width of the
former rectangle for the length of the deformed rectangle .
Denoting the length and width of a rectangle obtained at k-th time
by xk and yk , respectively, we have

On the other hand, from the condition that the area remains in deforming, the
width yk+1 is determined as follows.

From these two relations, the formula only concerning xk and xk+1 can be
obtained as follows.
The following program finds the first 8 terms of this sequence xk.

Example 20.
10 INPUT a
20 LET x=a
30 FOR n=1 TO 8
40 LET x=(x+a/x)/2
50 PRINT n,x
60 NEXT n
70 END

2.7.2 Numerical values of BASIC

All numerical values are expressed as decimals in Decimal BASIC. And for
such an operation that a correct value can be expressed in a 16-digit decimal, a
correct result can be obtained (not guaranteed).
For example, the calculation result of SQR(36) will accurately become 6. If the
angle measure is degree, the calculation result of SIN(30) will become 0.5. If
the true value of the calculation result cannot be expressed in 16-digit decimals,
however, the result will be an approximate value. For example, the calculation
result of 1/3 contains an error.
A numerical variable has the precision of 15 digits in Decimal BASIC. If you
substitute a numerical value that has over 15 significant digits for a variable, it
is rounded so that it has just 15 significant digits.
On the other hand, calculation results of numerical expressions have precision
of more than 16 digits. For example, the calculation result of 1/3 becomes
0.333333333333333333333333333, which has 27 significant digits.
Ordinarily, calculation results are displayed rounded to 15 digits, however, if
More Places Displayed is checked with Option menu Precision, all digits
shall be displayed in the decimal mode.

It is due to the Full BASIC standard that number of significant digits of a


numerical expression is larger than that of a numerical variable, but sometimes
it causes phenomena difficult to understand. For example, the execution result
of line 20 in the following program is not zero. This is because of difference in
the number of digits to be rounded to.
10 LET A=1/3
20 PRINT 1/3-A
30 END

2.7.3 Cancellation of Significant Digits


10 LET A=1/3
20 PRINT A-0.33333333333333
30 END

When the above is executed, the value of A in line 20 becomes


0.333333333333333, and then the execution result becomes .
000000000000003.
However, the above result may be considered that the number of significant
digits dropped to 1 from the viewpoint in which the value assigned to A in 10
line is thought to be 1/3.

While the accuracy of the result of a single calculation is guaranteed by the


standard, when two results of calculations at least one of whose true value can
not be accurately expressed in 15 digits are operated under subtraction, such a
phenomenon occurs that the number of significant digits considerably
decreases if the two numbers are close to each other.
This phenomenon is cancellation of significant digits.

The derivative f' (a) of a function y=f(x) at x=a is defined by the limit of

average rate of change as an increment h approaches 0


indefinitely.
The following program is to investigate how the average rate of change at x=2,
for f(x)= , changes when the value of h is changed to 10-1, 10-2, 10-3, 10-4,
, 10-15.
The limit, as h approaches 0, is approximately 0.353553390593274 in
theoretical calculation, but the execution result shows that it moves away from
the correct value as h approaches 0. This is due to cancellation of significant
digits accompanying subtraction as described above.

Example 21.
10 DEF f(x)=SQR(x)
20 FOR i=1 TO 15
30 LET h=10^(-i)
40 PRINT h, (f(2+h)-f(2))/h
50 NEXT i
60 END

Execution Result
.1 .349241122458488
.01 .35311255026876
.001 .3535092074646
.0001 .353548971286
.00001 .35355294866
.000001 .3535533464
.0000001 .353553386
.00000001 .3535534
.000000001 .3535534
.0000000001 .353554
.00000000001 .35356
.000000000001 .3536
.0000000000001 .354
.00000000000001 .36
.000000000000001 .4

2.7.4 Pi ()

Since the perimeter of the regular n-gon inscribed in a circle of diameter 1

is , denoting the perimeter of the regular 2 k-gon by ak, we have

ak=
.
From the half-angle identity,

,
and so

cos90cos45cos 22.5
can be calculated successively.

Even though the calculation of ak must be made if we use ,


actually, it is not so successful.

As k becomes large, becomes close to 0, and so becomes close to


1.
For this reason, cancellation of significant digits occurs in the calculation of 1-

So, we choose
the relation

obtained from the double-angle identity, to calculate

sin 90sin 45 .

The following program calculates these values successively and outputs

2k and , starting with cos 90=0 and sin 90=1.


Example 22.
10 LET c=0 ! cos90
20 LET s=1 ! sin90
30 FOR k=2 TO 30
40 LET c=SQR((1+c)/2)
50 LET s=s/c/2
60 PRINT 2^k,2^k*s
70 NEXT k
80 END

2.7.5 PRINT USING

Format indication can be written in a PRINT statement. It is written in the


following form.
PRINT USING format_string: expressionexpressionexpression
The format string includes the formats for all the expressions.
The gaps between the formats are filled with space characters.
And then the format string is written enclosed with double quotation marks.

The following form is recommended for a format. For the details of the format
characters, see the standard.
####### for a positive integer.
Write #'s of the number of places. (Right-aligned on
display)
-------% for an integer (positive or negative).
Write minus signs of the number of places, and % at the
end.
#######.#### for a positive decimal.
#'s are written for integral part and decimal part.
-------%.#### for a decimal (positive or negative)

The decimal part is rounded off to the places specified by the format.
When the format is made, care should be taken so that the number of digits of
the integral part will not be short. Especially for the negative number, the place
for outputting the minus sign must be secured.

Example 23
10 FOR i=0 TO 17
20 LET n=10^i
30 PRINT USING "################### #.##############":n,(1+1/n)^n
40 NEXT i
50 END

Output result
1 2.00000000000000
10 2.59374246010000
100 2.70481382942153
1000 2.71692393223589
10000 2.71814592682522
100000 2.71826823717449
1000000 2.71828046931938
10000000 2.71828169254497
100000000 2.71828181486764
1000000000 2.71828182709990
10000000000 2.71828182832313
100000000000 2.71828182844545
1000000000000 2.71828182845769
10000000000000 2.71828182845891
100000000000000 2.71828182845903
1000000000000000 2.71828182845904
10000000000000000 2.71828182845905
100000000000000000 2.71828182845905

Example 24
10 FOR x=3.14159265 TO 3.14159266 STEP 0.000000001
20 PRINT USING "%.######### ---%.###############":x,SIN(x)
30 NEXT x
40 END

Output result
3.141592650 0.000000003589793
3.141592651 0.000000002589793
3.141592652 0.000000001589793
3.141592653 0.000000000589793
3.141592654 -0.000000000410207
3.141592655 -0.000000001410207
3.141592656 -0.000000002410207
3.141592657 -0.000000003410207
3.141592658 -0.000000004410207
3.141592659 -0.000000005410207
3.141592660 -0.000000006410207

Next
Back

3 Description of Algorithm
3.1 If ~ END IF blocks and IF statements
3.1.1 IF ~ ELSE ~ END IF

Example 25.
A program that displays the solution of the quadratic equation ax2+bx+c=0
when coefficients a, b, c are entered.
10 INPUT a,b,c
20 LET D=b^2-4*a*c
30 IF D>=0 THEN
40 PRINT (-b-SQR(D))/(2*a), (-b+SQR(D))/(2*a)
50 ELSE
60 PRINT "no solution"
70 END IF
80 END

This program selects the process depending on the value of


discriminant D = b2-4ac.
When D0, two solutions are calculated and displayed using the quadratic
formula, and otherwise, no solution is displayed.
The inequality sign is substituted by >= in BASIC.
Like this, IF ~ ELSE ~ END IF is used to describe the process that executes ~
when a certain condition is true, and otherwise executes ~ .
An IF ~ ELSE ~ END IF block is described in the form shown below.
IF condition THEN
~
ELSE
~
END IF
The portion ~ can consist of multiple lines, which may be even blocks as FOF
~ NEXT blocks or IF ~ ELSE ~ END IF blocks.
In addition, if there are no statements between the ELSE line and the END-IF
line, ELSE can be omitted.

3.1.2 IF ~ ELSEIF ~ ELSE ~ END IF

The Program in Example 25 displays two solutions when D=0. To separately


handle the process for D=0, the following will do,
100 INPUT a,b,c
110 LET D=b^2-4*a*c
120 IF D>0 THEN
130 PRINT (-b-SQR(D))/(2*a), (-b+SQR(D))/(2*a)
140 ELSE
150 IF D=0 THEN
160 PRINT -b/(2*a)
170 ELSE
180 PRINT "no solution"
190 END IF
200 END IF
210 END

but the same process can be written as follows.

Example 26.
100 INPUT a,b,c
110 LET D=b^2-4*a*c
120 IF D>0 THEN
130 PRINT (-b-SQR(D))/(2*a), (-b+SQR(D))/(2*a)
140 ELSEIF D=0 THEN
150 PRINT -b/(2*a)
160 ELSE
170 PRINT "no solution"
180 END IF
190 END

3.1.3 IF statement

The program in Example 25 can also be written as follows.


10 INPUT a,b,c
20 LET D=b^2-4*a*c
30 IF D>=0 THEN PRINT (-b-SQR(D))/(2*a), (-b+SQR(D))/(2*a) ELSE PRINT "no
solution"
40 END
If the number of the statements to be executed when the condition holds is only
one, the number of the statements to be executed when the condition fails is
only one, and if both of them are such statements called imperative statements,
an IF statement in the form of the following is available
IF condition THEN imperative_statement ELSE imperative_statement

LET statements, INPUT statements, PRINT statements, SET statements, PLOT


statements, RANDOMIZE statements, and so on are imperative statements.
But a IF statement is not an imperative statement, that is, any IF statement can
not be included in a IF statement of the above form.

If there is no statement to be executed when the condition is not true, the IF


statement is written in the form
IF condition THEN imperative_statement

For example, if you do not need to display no solution when D<0, the
following will do.
10 INPUT a,b,c
20 LET D=b^2-4*a*c
30 IF D>=0 THEN PRINT (-b-SQR(D))/(2*a), (-b+SQR(D))/(2*a)
40 END

3.1.4 How to write conditions

Inequalities ab , ab and ab are written like a<=b, a>=b and a<>b, respectively.
Complicated conditions can be described using AND, OR, NOT and
parentheses.
For example, conditions p and q, p or q are written as p AND q ,
p OR q ,respectively. NOT is written just before the subject to be negated.
Among AND, OR and NOT, NOT precedes AND and OR. Between AND and
OR, AND precedes OR. If you want to change the priority, you can use
parentheses.
Although a<x and x<b is written as a<x<b in mathematics, this style is not
used in BASIC.

Example 27.
A Program that finds the sum of three-digit positive integers that can be divided
by 3 or 8.
10 LET t=0
20 FOR n=100 TO 999
30 IF MOD(n,3)=0 OR MOD(n,8)=0 THEN
40 LET t=t+n
50 END IF
60 NEXT n
70 PRINT t
80 END

3.1.5 Pythagorean numbers

Three positive integers x, y, and z which satisfy the equation x2+y2=z2 are
called Pythagorean numbers.
To systematically seek Pythagorean numbers, we make such a program as
outputs x, y and z= SQR(x^2+y^2) when z is an integer changing the values of x
and y successively.
Whether z is an integer or not can be known by checking whether INT(z) agrees
with z.

The following program seeks Pythagorean numbers in the range of


1xy100.

Example 28.
10 FOR x=1 TO 100
20 FOR y=x TO 100
30 LET z=SQR(x^2+y^2)
40 IF INT(z)=z THEN PRINT x,y,z
50 NEXT y
60 NEXT x
70 END

[Note]
The above program will operate even with such old type BASIC as N88-
BASIC. But correct answers may not be obtained.
In Full BASIC, correct answers can be obtained by the above program, since
the result of a power or square root operation must be correct if it can be
expressed within the significant digits.

3.2 DO ~ LOOP
3.2.1 DO ~ LOOP

A DO statement and a LOOP statement form a pair which describes a


repetition.
Example 29. Endless loop
10 LET A=0
20 DO
30 LET A=A+1
40 PRINT A
50 LOOP
60 END

The statements written between the DO line and the LOOP line are repeatedly
executed. In the above program, line 30 and line 40 are repeatedly executed.
[Supplement] When the above program is executed, click or select Break
from the Run menu to abort the execution.

3.2.2 DO WHILE ~ LOOP

This type of a loop repeats while a condition holds.


Example 30.
10 LET A=0
20 DO WHILE A<100
30 LET A=A+1
40 PRINT A
50 LOOP
60 END

When line 20 in Example 29 is modified to the above, the repetition stops when
the value of A becomes 100.

DO WHILE ~ LOOP is written in the following form. The operation of this


structure is expressed in a flowchart as shown in the figure.
DO WHILE condition

LOOP

In this loop structure, the condition is checked before executing the process to
be repeated, so if the condition fails at the beginning, no repetition is executed.
In Example 30, for example, if line 10 is changed to 10 LET A=100, line 30 and
line 40 are never executed.

3.2.3 DO UNTIL ~ LOOP

DO UNTIL ~ LOOP is a repetitive structure specifying the condition to finish


the repetition.

Example 31
10 LET A=0
20 DO UNTIL A>=100
30 LET A=A+1
40 PRINT A
50 LOOP
60 END

Example 31 has the same meaning as Example 30 has. Generally, if negation is


used, DO WHILE ~ LOOP and DO UNTIL ~ LOOP can be mutually
replaced. UNTIL p is same as WHILE NOT p. The selection depends on
the intention of a program writer.

3.2.4 Factorization into prime factors

DO ~ LOOP enables a program that factorizes an entered positive integer.

A positive integer to be factorized is to be input into a variable n.


First, whether n is divisible by 2 is checked, and if so, 2 is output and n is
replaced with the number n divided by 2. This is repeatedly executed while n is
divisible by 2.
When n can no more be divided by 2, the divisor is increased to 3, and the same
as above is repeated.
What should be done next is to increase the divisor to 5 and then repeat in the
same way, but since it is difficult to have the computer answer the next prime, 1
is simply added to the divisor. Then the divisor next to 3 will be 4, but this will
cause no problem, because n has been divided by 2 as much as possible.

Example 32 Factorization into prime factors


110 INPUT n
120 LET f=2
130 DO UNTIL n=1
140 DO WHILE MOD(n,f)=0
150 PRINT f;
160 LET n=n/f
170 LOOP
180 LET f=f+1
190 LOOP
200 END

A variable f represents the divisor (maybe a factor). In line 120, the first divisor
2 is set.
Through the repetition from lines 140 to 170, dividing by f is done as much as
possible. When dividing can no longer be done, 1 is added to f (line 180).
This will be repeated in the DO ~ LOOP of line 130 through line 190, but the
repetition must be stopped in some time. The condition is when all the factors
are taken from n, and it is n=1. This is the condition written in line 130.

3.2.5 EXIT DO

An EXIT DO statement is an instruction to finish the repetition of a DO ~


LOOP and moves the control to the next line of the LOOP statement.
DO WHILE ~ LOOP or DO UNTIL ~ LOOP decides whether the body of the
loop should be executed or not before it is executed.
But sometimes the decision is impossible at the beginning of a loop. In such a
case, an EXIT DO statement is used.

The following program demands input repeatedly until a correct answer is


input. In this case, it can not be judged before the input whether it is correct or
not.

Example 33
10 PRINT "23=?"
20 DO
30 INPUT n
40 IF n=2*3 THEN EXIT DO
50 PRINT "Incorrect. Type Again."
60 LOOP
70 PRINT "Right"
80 END

The flow of processing of Example 33 is shown in the figure.


3.2.6 Base conversion

We make a program that expresses an entered positive integer in base 2.


Let n =11, for instance.
As 11=123+022+12+1, 11 is expressed as 1011 in base 2.
If you want to successively find these from the lower digit, do as shown below.

211 1
2 5 1
2 2 0
2 1 1
0

Since the quotient of a divided by b is obtained by INT(a/b) and the remainder


by MOD(a,b), the following program is obtained.

Example 34.
10 INPUT n
20 DO
30 LET q=INT(n/2)
40 LET r=MOD(n,2)
50 PRINT r
60 IF q=0 THEN EXIT DO
70 LET n=q
80 LOOP
90 END

3.2.7 Euclidean algorithm

We denote the greatest common divisor of two integers a and b as GCD(a,b).


Then we have:

Let r be the remainder when a is divided by b.


If r = 0 then GCD(a,b) = b, otherwise GCD(a,b) = GCD(b,r).

The greatest common divisor of two positive integers can be found when this
property is repeatedly used as follows. This is called the Euclidean algorithm.

Divide a by b, and let r be the remainder.


If r=0 then b is the greatest common divisor.
If r>0 then this operation is executed again with b,r made new a,b.

In this operation, the value of b decreases each time it is repeated, and it will
surely end after some repetitions.

Example 35.
A program that finds the greatest common divisor using Euclidean algorithm.
10 INPUT a,b
20 DO
30 LET r=MOD(a,b)
40 IF r=0 THEN EXIT DO
50 LET a=b
60 LET b=r
70 LOOP
80 PRINT b
90 END

It should be noted that assignment statements are used in such an order as


shown in line 50 and line 60 to make the value of b,r the next value of a,b at the
end of the repetition.

3.3 Arrays
3.3.1 DIM statement

In the beginning of a program, write


DIM A(10)
to prepare 10 variables
A(1)A(2)A(3)A(4)A(5)A(6)A(7)A(8)A(9) and A(10),
which can be used as ordinary variables.
A group of such variables is called an array, while each variable is called an
indexed variable or an element of the array, and each number within the
parentheses is called an index or a subscript.
Example.
10 DIM A(10)
20 LET A(4)=15
30 PRINT A(4)
40 END

In a DIM statement, the name of an array and the upper bound of indices are
written in the form as shown above. The rule for naming an array is the same as
for an ordinary variable. Note that only constants like 10, 20 can be written for
the upper bound of indices.

[Note] Handling of arrays is different from that in minimal BASIC, the former
standard for BASIC. Especially, it should be noted that the array index starts
with 1.

On indexed variables, an expression containing a variable can be written for an


index. For example:
10 DIM B(4)
20 LET i=3
30 LET B(i)=17
40 PRINT B(i)
50 END

If this feature is utilized, it becomes possible to select a variable on executing a


program.
Such variable names as B1, B2 and B3 can be used In BASIC. In such a case,
however, the numeric portions such as 1, 2 and 3 are part of variable names,
and therefore, it is impossible to select any of B1, B2 or B3 by specifying a
number with a program.

Example 36. Fibonacci Series.


The Fibonacci series { fn } is defined by f1=1 f2=1 fn = fn-1+fn-2 (n = 3, 4,
5, ).
The following program finds the first 20 terms of he Fibonacci series using an
array.
100 DIM f(20)
110 LET f(1)=1
120 LET f(2)=1
130 FOR i=3 TO 20
140 LET f(i)=f(i-1)+f(i-2)
150 NEXT i
160 FOR i=1 TO 20
170 PRINT i,f(i)
180 NEXT i
190 END

3.3.2 Frequency Distribution Table

Array can be utilized for making distribution tables.


Here we make a program that creates a frequency distribution table with class
width 10 to summarize the scores of an examination of which full marks is 100
points, for example.
We prepare 11 indexed variables from m(0) to m(10), and represent the number
of persons of 0 point to 9 points by m(0), the number of persons of 10 points to
19 points by m(1), the number of persons of 20 points to 29 points by m(2), and
so on.
In order to use 11 indexed variables m(0),m(1), ... , m(10), we write such a
DIM statement as
DIM m(0 TO 10)

in the beginning of the program.


Then we write
MAT m=ZER

to substitute zeros for all the elements of the array m.


When a score is entered, an index i, which indicates the rank, is calculated and
1 is added to the indexed variable indicated by the index i.
A negative number is to be entered for the end mark on finishing of input of all
the scores.

[Note] MAT is the first 3 letters of matrix.

Example 37.
100 DIM m(0 TO 10)
110 MAT m=ZER
120 DO
130 INPUT n
140 IF n<0 THEN EXIT DO
150 LET i=INT(n/10)
160 LET m(i)=m(i)+1
170 LOOP
180 FOR i=0 TO 10
190 PRINT i*10;" ~ ";i*10+9,m(i)
200 NEXT i
210 END

Example 38.
A program that repeats 10000 times the simulation of finding the sum of spots
on 10 dice, totalizes the results and displays them in a histogram.
100 DIM A(10 TO 60)
110 MAT A=ZER
120 FOR k=1 TO 10000
130 LET t=0
140 FOR n=1 TO 10
150 LET t=t+INT(RND*6+1)
160 NEXT n
170 LET A(t)=A(t)+1
180 NEXT k
190 SET WINDOW 9,61,0,1000
200 FOR t=10 TO 60
210 PLOT LINES: t-0.5,A(t); t+0.5,A(t);
220 NEXT t
230 END

Since the sum of the spots is in the range of 10 to 60, an array A with indices in
the same range is prepared.
3.3.3 Sieve of Eratosthenes

The set of prime numbers can be obtained by the method of successively


removing the composite numbers from the set of integers to leave only the
prime numbers. This method has long well been known as the sieve of
Eratosthenes.
Preparing a table with 2 or more integers sequentially arranged and marking
composite numbers n2, (n+1)n, (n+2)n, , multiples of n for n=2,3,4,, prime
numbers will remain last.

We prepare an array s with indices from 2 to 1000 and represent an integer n by


an indexed variable s(n), expressing that n is marked by s(n)=1 and not by
s(n)=0.

Example 39.
100 DIM s(2 TO 1000)
110 MAT s=ZER
120 FOR n=2 TO 1000
130 IF s(n)=0 THEN
140 PRINT n
150 FOR k=n^2 TO 1000 STEP n
160 LET s(k)=1
170 NEXT k
180 END IF
190 NEXT n
200 END

if an integer n is not marked when the process of marking all multiples of k is


completed for all integers k with 2k<n, n can be judged to be prime.
The process is rationalized using this property, so that all are processed in
FOR~NEXT at lines 120~190.
The multiples of n are marked by FOR~NEXT at lines 150~170.
When the value of k is sequentially increased by n from n 2, the value of k may
not become 1000, but the repetition ends when the value of k exceeds 1000
because of the property of FOR~NEXT , and so the program operates without
problem.

3.3.4 Array declaration

Two-dimensional or three-dimensional arrays are also available.


For example, when DIM A(2,3) is written, 6 indexed variables, A(1,1), A(1,2),
A(1,3), A(2,1), A(2,2), and A(2,3), are prepared.
More than one array can be declared in a DIM statement. In such a case, array
declarations are delimited by commas. For example,
DIM A(4),B(10),C(20)

Indices of an array are regarded to start with 1 in Full BASIC.


If you want indices to start with 0, write OPTION BASE 0 in a line above the
line where the first array declaration is written as shown below.
10 OPTION BASE 0
20 DIM A(4)
30 LET A(0)=7
40 MAT PRINT A
50 END

If you desire to make the lower bound other than 0 or 1, or different for each
array, use such a DIM statement as shown below.
DIM A(-4 TO 5),B(0 TO 2, 1 TO 3)

In this array declaration, 10 indexed variables from A(4) to A(5) and 9


indexed variables from B(0,1) to B(2,3) are prepared.

3.3.5 Binomial coefficient (Pascals triangle)

Let's make Pascal's triangle or the table of number of combinations nCr utilizing
a two-dimensional array.
We use the following recurrence to calculate nCr.
When r = 0 or r = n, nCr = 1
When 0<r<n, nCr = n-1Cr-1 +n-1Cr

Example
100 DIM C(1 TO 10, 0 TO 10)
110 MAT C=ZER
120 FOR n=1 TO 10
130 FOR r=0 TO n
140 IF r=0 OR r=n THEN
150 LET C(n,r)=1
160 ELSE
170 LET C(n,r)=C(n-1,r-1)+C(n-1,r)
180 END IF
190 NEXT r
200 NEXT n
210 MAT PRINT C;
220 END
With the MAT PRINT statement used in line 210, the values of all indexed
variables belonging to the array are collectively output. If a semicolon is
written following the array name as in line 210, the numerical values are
closely output.

3.3.6 MAT statement (input/output)

Full BASIC prepares devices convenient for processing arrays. For example,
MAT INPUT statements and MAT PRINT statements make array input and
output easy.

Example 41.
10 DIM A(5)
20 MAT INPUT A
30 MAT PRINT A
40 END

A MAT INPUT statement inputs numerical values collectively to an array.


When the MAT INPUT statement in line 20, for example, is executed, 5
numerical values are to be input by delimiting by commas.
A MAT PRINT statement collectively outputs the values of all the indexed
variables belonging to an array.
If such a MAT PRINT statement without semicolon written after the array
name as in line 30 is executed, the numerical values are output at fixed
positions.

A MAT READ statement substitutes numerical values for arrays from the
DATA statements.
In the DATA statement, necessary number of numerical values should be
written by delimiting by commas.
This is convenient when you want to enter the same data each time in programs
in test stages.

Example 42. A program that finds the smallest value.


10 DIM A(10)
20 DATA 45,61,73,91,43,12,65,34,96,12
30 MAT READ A
40 LET k=1
50 FOR i=2 TO 10
60 IF a(i)<a(k) THEN LET k=i
70 NEXT i
80 PRINT a(k)
90 END

3.3.7 SortSelection Sort

We make a program that arranges entered 10 numerical values in increasing


order.
We assume that 10 numerical values are entered to 10 indexed variables from
a(1) to a(10).
We first exchange the smallest value in a(1), a(2), , a(10) with a(1). Then a(1)
becomes the smallest.
Next, the smallest one of the values from a(2) to a(10) is exchanged with a(2).
Then a(2) becomes the second smallest.
If the similar process is executed repeatedly, the numerical values are arranged
in increasing order in the array a.

Example 43.
100 DIM a(10)
110 MAT INPUT a
120 FOR i=1 TO 9
130 LET k=i ! k is the index of the smallest
value.
140 FOR j=i+1 TO 10
150 IF a(j)<a(k) THEN LET k=j
160 NEXT j
170 LET t=a(i) ! using t as a temporary variable,
180 LET a(i)=a(k) ! exchange the values in a(k) and
a(i).
190 LET a(k)=t
200 NEXT i
210 MAT PRINT a;
220 END

Lines 130~160 are the process of acquiring the index of the smallest value in
a(i)~a(10) for variable k.
In lines 170~190, a temporary variable t is used to exchange the values of a(i)
and a(k).
The portion of a line subsequent to ! is a comment. This does not affect the
execution of a program. Comments are used for explaining the meaning of the
program.
To see how this program is operating, you can move the MAT PRINT statement
in line 210 to the suitable position.

3.3.8 Insertion Sort


By using a recursive way of thinking, you can make a sorting algorithm of
rather different type.
If a(1)~a(i-1) are already arranged in increasing order, a(1)~a(i) will be
arranged in increasing order by inserting the value of a(i) in the proper position
and shifting the subsequent values backwards sequentially.
Then if you repeat the aforementioned process sequentially from i=2 to i=10,
they will be arranged in increasing order.

Example 44.
100 DIM a(10)
110 MAT INPUT a
120 FOR i=2 TO 10
130 LET b=a(i) ! a(i) is saved to b.
140 LET j=i ! j will means the position for
inserting b.
150 DO WHILE j>1 AND a(j-1)>b
160 LET a(j)=a(j-1) ! Shift the data backwards.
170 LET j=j-1
180 LOOP
190 LET a(j)=b
200 NEXT i
210 MAT PRINT a;
220 END

In lines 130~180, the position for inserting the value of a(i) is sought,
accompanied by the process of shifting the values in the variables backwards.
In the AND operation in line 150, the sequence of j>1 and a(j-1)>b is
important.
When j=1 , the condition j>1fails so that a(j-1)>b will not be tested.
In line 150, j=1 may occur, and so if a(j-1)>b were tested before j>1, the
index would be out of range, resulting in an error.

3.4 Exception Handling


3.4.1 Error during execution (Exception)

If PRINT is spelled as PRIMT or NEXT corresponding to FOR does not exist,


the compiler reports an error. This is a syntax error.
If 1/x is calculated when the value of x is 0, an error occurs, of course.
In BASIC, the largest number which can be handled is settled, and if the
absolute value of the calculation result exceeds that value (MAXNUM), the
error occurs (overflow).
Such errors that occur during execution are called exceptions and are
discriminated from syntax errors.

The zero division error can be prevented by checking the divisor in advance of
the division, but it is hardly possible to predict the overflow error. In such a
case, action must be taken only after the error has occurred.

3.4.2 WHEN EXCEPTION structure

A WHEN EXCEPTION structure indicates the process to be executed when an


exception has occurred.
We write these in the following form.
WHEN EXCEPTION IN

Processes that may cause an exception

USE

The process to be executed when an exception has occurred

END WHEN

If an exception occurs in a statement written between a WHEN-EXCEPTION-


IN line and a USE line, the execution of the statement is suspended and the
control is moved to the line following the USE line.
On the other hand, if all the statements written between a WHEN-
EXCEPTION-IN line and a USE line has been executed without causing an
exception, statements written between the USE line and the END-WHEN line
shall not be executed.

This structure is indispensable for drawing function graphs.

Example 46 The graph of y = tan x


100 OPTION ANGLE DEGREES
110 DEF f(x)=TAN(x)
120 SET WINDOW -180,180,-4,4
130 DRAW AXES(90,1)
140 FOR x=-180 TO 180
150 WHEN EXCEPTION IN
160 PLOT LINES: x,f(x);
170 USE
180 PLOT LINES
190 END WHEN
200 NEXT x
210 END

If the PLOT LINES at line 180 does not exist, the line segment connecting two
points (89, TAN(89) and (91,TAN(91)), for example, shall be drawn.

Next
Back

4 Program Segmentation
4.1 External Function Definition
4.1.1 Necessity of program segmentation

Example 28 generates meaningless Pythagorean numbers such as 6, 8, and 10.


In order to prevent this, all we have to do is to exclude x and y whose greatest
common divisor is greater than 1, so we can do that by implanting Example 35
directly into Example 28 as shown below.
100 FOR x=1 TO 100
110 FOR y=x TO 100
120 LET a=x
130 LET b=y
140 DO
150 LET r=MOD(a,b)
160 IF r=0 THEN EXIT DO
170 LET a=b
180 LET b=r
190 LOOP
200 IF b=1 THEN
210 LET z=SQR(x^2+y^2)
220 IF INT(z)=z THEN PRINT x,y,z
230 END IF
240 NEXT y
250 NEXT x
260 END

However, it is not easy to make such a program in many case. For example, if
Example 28 uses a, b, c instead of x, y, z as variable names, the combined
programs will not operate normally.

4.1.2 External function definition

BASIC provides us with many built-in functions, but they are not sufficient.
DEF statements enables us to define a function, but only a function that can be
indicated by an expression. BASIC also provides us with facilities with which
we can define such a function that can only be found through more complicated
processing.
The program shown in the preceding paragraph can be more easily written by
denoting the greatest common divisor of 2 numbers a and b as GCD(a,b). To do
this, we use an external function definition, so called.
In BASIC, the portion to the END line is called a main program. And the
END line is followed by what are called external procedures. An external
function definition is one type of a external procedure.
In Example 47, the portion from line 200 to line 280 is the external function
definition to define the GCD function. An external function definition starts
with an EXTERNAL FUNCTION line and ends with an END FUNCTION
line. The EXTERNAL FUNCTION line holds the name of the function and the
parameter list, which is parenthesized. If there are two or more parameters, they
are delimited with commas.

Example 47
100 DECLARE EXTERNAL FUNCTION GCD
110 FOR x=1 TO 100
120 FOR y=x TO 100
130 IF GCD(x,y)=1 THEN
140 LET z=SQR(x^2+y^2)
150 IF INT(z)=z THEN PRINT x,y,z
160 END IF
170 NEXT y
180 NEXT x
190 END
200 EXTERNAL FUNCTION GCD(a,b)
210 DO
220 LET r=MOD(a,b)
230 IF r=0 THEN EXIT DO
240 LET a=b
250 LET b=r
260 LOOP
270 LET GCD=b
280 END FUNCTION

The main program and external procedures are called program units.
In a program unit that uses an external function, a declaration statement that
holds the name of the external function is written. In the above program, such a
declaration statement as line 100 is written to use GCD as the external function
in the main program. Writing such a declaration statement makes it possible to
do correct operation even if there is a built-in function whose name is the same
as the name of the external function. The declaration statement is written in a
line above where the function is actually used.
As for the syntax, just the needed function name is written succeeding
DECLARE EXTERNAL FUNCTION.
[Note]
With regard to the present version of Decimal BASIC, we can omit the
declaration of the external function that does not agree in name with any
built-in function, but declaration statements should be always written
because the built-in function names may increase in future. And we are
considering to change the syntax so as not to allow the omission of the
external function declaration in future version.
In the above program, the GCD function is used in line 130. This is called
an invocation of the function. Parameters, such as x and y in the above
program, written in an invocation are called arguments.
When the GCD function is invoked, the values of the arguments are substituted
for the variables a, b, and then the lines of the function definition are executed.
The value of the function is decided by a LET statement in the form of
substituting for the function name as in line 270.

Each program unit is independent as to variable names. Even if there is a


variable of the same name in another program unit, it is a different variable on
the computer. For example, if the variables x, y, z in the main program of
Example 47 are changed to a, b, c, the program will operate normally.

4.1.3 Greatest common divisor of 3 numbers

Utilizing the external function definition makes it easy to find the greatest
common divisor of 3 numbers. It is done as follows:
100 DECLARE EXTERNAL FUNCTION GCD
110 INPUT a,b,c
120 PRINT GCD(GCD(a,b),c)
190 END
200 EXTERNAL FUNCTION GCD(a,b)

Same as Example 47

280 END FUNCTION

4.1.4 Recursive invocation

As to a factorial n!, the recurrence formula 0!=1, n!=n(n1)! holds.


Therefore 7! can be found by multiplying 6! by 7. Then 6! can be found by
multiplying 5! by 6. When we decrease the numerical values like the above,
finally we reach the formula 0!=1 to solve the problem.
The method to solve a problem by repeatedly recurring to a problem similar but
smaller in this manner is called recurrence.
In BASIC it is allowed to invoke itself in a function definition. In the following
program, the function FACT uses itself to calculate the factorial in its
definition.

Example 48. Factorial


10 DECLARE EXTERNAL FUNCTION FACT
20 INPUT n
30 PRINT FACT(n)
40 END
100 EXTERNAL FUNCTION FACT(n)
110 IF n=0 THEN
120 LET FACT=1
130 ELSE
140 LET FACT=n*FACT(n-1)
150 END IF
160 END FUNCTION
In computer programming, invoking itself in a function defining is known as
a recursive invocation. The reason why the recursive invocation goes well in
BASIC is that the variables are allocated anew each time the function is
invoked. For example, even if line 140 is replaced with LET FACT=FACT(n1)*n,
the program actually operates correctly. But if the value of n changes in the
course of calculation of FACT(n1), it should not correctly operate. That is, each
time the function FACT is invocated, the variable n valid only for that
invocation is allocated anew to a different place in the memory.

4.1.5 Euclidean algorithm

The Euclidean algorithm, which finds the greatest common divisor, is also a
typical example of recursive algorithm. This algorithm can be written in
BASIC as follows.

Example 49
10 DECLARE EXTERNAL FUNCTION GCD
20 INPUT a,b
30 PRINT GCD(a,b)
40 END
100 EXTERNAL FUNCTION GCD(a,b)
110 LET r=MOD(a,b)
120 IF r=0 THEN LET GCD=b ELSE LET GCD=GCD(b,r)
130 END FUNCTION

4.2 External Picture Definition and External


Subprogram
4.2.1 External picture definition

Full BASIC is not provided with an instruction to draw a circle, but it is


provided with means to define the instruction to draw a circle. That is called
a picture definition.

Example 50
10 DECLARE EXTERNAL PICTURE circle
20 OPTION ANGLE DEGREES
30 SET WINDOW -8,8,-8,8
40 DRAW circle
50 DRAW circle WITH SCALE(2)
60 DRAW circle WITH SCALE(3,2)
70 DRAW circle WITH SCALE(3,2)*SHIFT(3,4)
80 DRAW circle WITH SCALE(5,3)*ROTATE(60)
90 END
100 EXTERNAL PICTURE circle
110 OPTION ANGLE DEGREES
120 FOR t=0 TO 360
130 PLOT LINES:COS(t),SIN(t);
140 NEXT t
150 END PICTURE

The portion from line 100 to line 150 is called an external picture definition. In
the first line of the external picture definition, the picture name is written
following EXTERNAL PICTURE. In the above program, circle is the
picture name. An parameter list part can be written as in the case of external
function definitions, if necessary.
The picture circle draws a circle of radius 1 with center the origin. to be exact, a
regular 360-gon is drawn, but it looks like a circle on the display of the
computer.
Each program unit is independent as to OPTION statements. Even if OPTION
ANGLE DEGREES is written in the main program, the unit of angle measure
is not changed in an external picture definition.
A DRAW statement is used for executing a picture. Such transformation as
rotating or scaling with center the origin, or translation can be specified in a
DRAW statement.
SCALE(a,b) stands for an expansion of a-fold in the x-axis direction and b-
fold in the y-axis direction with the center at the origin, where a and b can be
negative numbers. In the case of a=b, it can be written as SCALE(a).
SHIFT(a,b) stands for a translation that moves the origin to the point (x, y).
ROTATE() stands for a rotation of angle with the center at the origin.
Transformations can be composed with *. The composing transformations are
executed from the left. For example, SCALE(3,2)*SHIFT(3,4) is scaling first
and then parallel shifting.

4.2.2 External subprogram

All of the functionalities of an external subprogram are included in those of


an external picture definition, provided that subprograms have no ability of
transformation of graphics.

Example 51.
100 DECLARE EXTERNAL SUB circle
120 SET WINDOW -4,4,-4,4
130 CALL circle(1,-1,2)
140 END
200 EXTERNAL SUB circle(a,b,r)
210 OPTION ANGLE DEGREES
220 FOR t=0 TO 360
230 PLOT LINES: a+r*COS(t),b+r*SIN(t);
240 NEXT t
250 END SUB

Example 51 defines a subprogram circle (a,b,r) that draws a circle of radius r


with center at (a, b).
Use a CALL statement to invoke a subprogram. If a subprogram has
parameters, the parameters list is described in the same format as for a
function.

4.2.3 Variable parameter (pass by reference)

The picture and subprogram have some characteristics different from the
function definition.
One of those is variable parameter (pass by reference).

Example 52
10 DECLARE EXTERNAL SUB double
20 LET a=3
30 CALL double(a)
40 PRINT a
50 END
100 EXTERNAL SUB double(x)
110 LET x=x*2
120 END SUB

In Example 52, the subprogram double(x) doubles the value of the variable
written as an argument.
If a variable is written as an argument of a CALL statement, the invoked
subprogram uses the actual area of the variable on the memory as the memory
area for the parameter to which the variable has been assigned. Therefore, if the
value of the parameter is changed during the execution of the subprogram, the
value of the variable also changes.
If the argument is not a variable, for example, a constant, an arithmetic
operation or a parenthesize variable, the parameter to which the argument is
assigned is allocated to a new memory area and the value of the argument is
substituted for it.
For example, if line 30 is changed to CALL double (1*a), just the numerical
value of the calculation result of 1*a is passed to the subprogram and the value
of the variable a does not changes.
4.2.4 Extended Euclidean algorithm

We consider a problem to find an integer solution of an equation ax+by = c,


where a, b, c are integer constants.
When b=0, the solution is obvious. If c can be divided by a, the solution
is x=c/a, y can be any, so let y=0.
Conversely, if c cannot be divided by a, there is no solution.
When b0, let q be the quotient when a is divided by b, and r the remainder.
Since a=bq+r, the original equation can be replaced by b(qx+y)+rx=c.
Then, if the solution of the equation bu+rv=c is obtained, the solution
is x=v, y=uqv, and if there is no solution for bu+rv=c, the equation has no
solution.
Here the solution of bu+rv=c is always fixed. This is because
when ax+by = c and bx+ry=c are compared, the coefficient of y is surely
close to 0. Since the coefficient of y is an integer, it will surely become 0 after
several repetitions.

Example 53.
10 DECLARE EXTERNAL SUB solve
20 INPUT a,b,c
30 WHEN EXCEPTION IN
40 CALL solve(a,x,b,y,c)
50 PRINT x,y
60 USE
70 PRINT "no solution"
80 END WHEN
90 END
100 EXTERNAL SUB solve(a,x,b,y,c)
110 IF b=0 THEN
120 IF MOD(c,a)=0 THEN
130 LET x=c/a
140 LET y=0
150 ELSE
160 CAUSE EXCEPTION 999
170 END IF
180 ELSE
190 LET q=INT(a/b)
200 LET r=MOD(a,b)
210 CALL solve(b,u,r,v,c)
220 LET x=v
230 LET y=u-q*v
240 END IF
250 END SUB
A CAUSE EXCEPTION statement (in line 160) causes an exception of the
specified number. The exception numbers of 1 to 999 are reserved for users.
If the statement that has caused the exception is not enclosed by a WHEN
EXCEPTION USE, the exception is propagated to the invoking statement.

Next
Back

5 Data input and output


5.1 Character string
5.1.1 String constant

When a character string is described in a program, it is enclosed in double


quotation marks. The character string enclosed in double quotation marks is
called a string constant. When a double quotation mark is included in the
character-string constant, it is doubled like "".
Example 54
10 PRINT "Say ""Hello!"""
20 END

5.1.2 String variable

A variable having the character string as a value is called a string variable. In


BASIC, any string variable is named using a $ (dollar symbol) at the end.

5.1.3 String concatenation

For character strings, concatenation operation is defined. String concatenation


is expressed by writing & between the character strings.
Example 55.
10 LET s$="Brown"
20 LET s$="Mr. " & s$
30 PRINT s$
40 END

5.1.4 STR$ function


The built-in function STR$(x) converts a numerical value x to a string. No
blank character shall be included before or after the numerical value.
The following program converts the input value to a binary representation and
displays it in such a way that the most significant digit comes to the left.
56
10 INPUT n
20 LET s$ = ""
30 DO UNTIL n=0
40 LET r = MOD(n,2)
50 LET s$ = STR$(r) & s$
60 LET n = (n-r)/2
70 LOOP
80 PRINT s$
90 END

A character string that has no character is called a null string. a null string is
expressed by "".
In the above program, s$ is made a null string first, and each time the input
value is divided by 2, the remainder is converted to a character string and then
concatenated to the left of s$.

5.2 DATA statement


5.2.1 READ statements and DATA statements

BASIC is provided with syntax to describe data in a program.


Data are described in a DATA statement delimiting with commas.
The instruction to read data into variables is a READ statement. When two or
more variables are written in a READ statement, they are delimited with
commas.
Data items are read in the variables in the sequence how they are written in a
DATA statement.
Example 57.
10 DATA 1,2,3,4,5,6,7,8,9,10
20 FOR i=1 TO 5
30 READ a,b
40 PRINT a,b
50 NEXT i
60 END

When all data cannot be written in one line, they can be written in multiple
DATA statements.
In such a case, no comma is written at the end of a line. (If so, a syntax error
shall occur.)
For example, the DATA statement in the above program can be split into three
statements as shown below.
10 DATA 1,2,3,4
12 DATA 5,6,7,8
14 DATA 9,10

5.2.2 READ IF MISSING THEN

In the above example, 5 sets of data, 2 pieces per set, are prepared, and so the
FOR~NEXT loop is repeated 5 times to read the data, but it is troublesome if
the data quantity is indefinite or unknown.
Full BASIC is provided with an instruction to read an indefinite quantity of
data.
If IF MISSING THEN EXIT DO: is written between READ and the first
variable name in a READ statement in a DO~LOOP, the repetition of the
DO~LOOP shall be finished when data is no longer available.
The following example is a program to calculate the average of data written in
a DATA statement.
Example 58.
100 DATA 34,71,85,80,58,49,52,13
110 LET n=0
120 LET t=0
130 DO
140 READ IF MISSING THEN EXIT DO: x
150 LET t=t+x
160 LET n=n+1
170 LOOP
180 PRINT t/n
190 END

5.2.3 RESTORE statement

A RESTORE statement makes READ statements read data from the first again.
The following program calculates the difference from the mean, or the
deviation, for each data. Since the mean must be calculated before the
calculation of the deviation, the data should be read twice.
Example 59.
100 DATA 34,71,85,80,58,49,52,13
110 LET n=0
120 LET t=0
130 DO
140 READ IF MISSING THEN EXIT DO: x
150 LET t=t+x
160 LET n=n+1
170 LOOP
180 LET m=t/n ! the mean
190 RESTORE
200 FOR i=1 TO n
210 READ x
220 PRINT x-m ! the deviation
230 NEXT i
240 END

5.3 Files
5.3.1 OPEN statement and CLOSE statement

It is posible to input data from a text file, or output results to a text file. A text
file is the simplest type a file, which can be read and written with NotePad of
Windows or other text editors.
When a file is used, it is assigned to a virtual existence called a channel.
Channels are identified by positive integers. Commonly, small numbers such as
1 and 2 are used sequentially.
The instruction to assign a file to a channel is an OPEN statement. An OPEN
statement is written in the following form.
OPEN #Channnel_Number NAME File_Name
In the above, Channnel_Number is a numeric expression and File_Name is a
string expression.
When the use of a file is completed, a CLOSE statement is executed. A CLOSE
statement is written in the following form.
CLOSE #Channel_Number

5.3.2 Input from a file

If the same content as the input reply to an INPUT statement is written in a text
file, data can be continuously input from the file. The input reply corresponding
to one execution of an INPUT statement corresponds to one line in a text file,
but we can write an input reply in multiple lines, writing a comma at the end of
a line.
When input is made from a file, an INPUT statement is written in the following
form. INPUT #Channel_Number: variable, variable, , variable
For example, if you want to input data from a file named DATA1.TXT on the
drive A, what you should make is such a program as shown below. Example 60
10 OPEN #1: NAME "A:\DATA1.TXT"
20 FOR i=1 TO 4
30 INPUT #1:s$,n
40 PRINT s$,n
50 NEXT i
60 CLOSE #1
70 END

A:DATA1.TXTin the above is a file name on Windows. The way to specify


the file depends on OS.
In DATA1.TXT, a string constant and a numerical constant corresponding to
the input of line 30 are written in a line delimiting with a comma, and such four
lines are to be prepared as follows.
"Yamada", 78
"Suzuki", 90
"Sakai", 100
"Okano", 76

They can also be written in 8 lines by line-feeding just after the comma.
If an INPUT statement with IF MISSING THEN EXIT DO is used in a
DO~LOOP, it is possible to prepare a program that copes with an indefinite
number of input.
In this case, IF MISSING is written to follow the channel number with a
comma.
61
10 OPEN #1: NAME "A:DATA1.TXT"
20 DO
30 INPUT #1, IF MISSING THEN EXIT DO: s$,n
40 PRINT s$,n
50 LOOP
60 CLOSE #1
70 END

5.3.3 Output to a file

There are two methods, overwriting and appending, in writing to a file.


Overwriting erases any existing content in the specified file and replaces it with
new content. Appending writes to the end of the existing text.
For overwriting, an ERASE statement shall be executed just after the OPEN
statement is executed. If the file of the specified name does not exist, a new one
shall be created. It is no problem to execute an ERASE statement for an empty
file. Example 62
10 OPEN #2:NAME "A:DATA2.TXT"
20 ERASE #2
30 FOR x=1 TO 10
40 PRINT #2: x,SQR(x)
50 NEXT x
60 CLOSE #2
70 END

Outputting to a text file is done in the same form as to the screen. That is, it is
the same form as the contents of a file in which the contents of the text output
window are stored. Since blanks are output between items, it is not suitable to
re-reading with BASIC, but it can be read into a spreadsheet such as EXCEL if
spaces is specified for the delimiter.
In case of appending, change line 20 to
20 SET #2: POINTER END

5.3.4 File of internal record type

If data with more than one item is output as a text file, it cannot be re-read with
BASIC, but if internal record type is used, the data output with BASIC can be
re-read with BASIC. In order to use internal record type, RECTYPE
INTERNAL is added to the end of an OPEN statement, a WRITE statement is
used for output in place of a PRINT statement, and a READ statement is used
for input in place of an INPUT statement.
Since the actual form of internal record type of Decimal BASIC is a comma-
separated text (CSV), it can be used for data exchange with a spreadsheet
program, etc.
Example63.
Outputting in internal record type
10 OPEN #1:NAME "A:DATA2.CSV" ,RECTYPE INTERNAL
20 ERASE #1
30 FOR x=1 TO 10
40 WRITE #1: x,SQR(x)
50 NEXT x
60 CLOSE #1
70 END

Example 64.
Reading a file of internal record type
10 OPEN #1: NAME "A:DATA2.CSV" ,RECTYPE INTERNAL
20 DO
30 READ #1, IF MISSING THEN EXIT DO: x,y
40 PRINT x,y
50 LOOP
60 CLOSE #1
70 END

READ statements and WRITE statements can be used in a file of not internal
record type, but in such a case, the effect is same as for INPUT statements and
PRINT statements.
Next
Back

Appendix

Appendix 1. Reserved words in Full BASIC

The following keywords are reserved words, which cannot be used for
identifires (variable names, function names, or routine names).
NOTELSEPRINTREMPIRNDMAXNUMTIMEDATEEXTYPEEXLINEZERC
ONIDNTRANSFORM

Appendix 2. Other important instructions

1. Control
EXIT FOR escapes from the FOR ~ NEXT. (Similar to EXIT DO)

GOTO line_number The control is moved to the line with a specified line
number.

EXIT DO and EXIT FOR escapes from the innermost DO~LOOP ,


FOR~NEXT, respectively.
To escape from the outside loop, jumping over the inside loop,
use a GOTO statment.

2. Graphics
wait for clicking with the mouse, and substitutes the
GET POINT: x, y
coordinates of that point for the variable x, y.

PLOT AREA: x2, y2 ; fills the inside of the area surrounded by a polygonal
x2, y2; ... ; xn, yn line connecting (x1, y1), (x2, y2), , (xn, yn), (x1, y1).

SET AREA
Area color is made n. (Similar to SET LINE COLOR)
COLOR n

Appendix 3. Major Built-in Functions (only numeric)

General

ABS(x) Absolute value of x

SQR(x) Nonnegative square root of x


INT(x) The largest integer not exceeding x

MOD(x, y) Remainder when x is divided by y

CEIL(x) The smallest integer not less than x

IP(x) Integral part of x

FP(x) Fraction part of x

ROUND(x, n) Value of x rounded to n places of decimals

Sign of x. SGN(x)=1 when x>0, SGN(0)=0, SGN(x)=-1 when


SGN(x)
x<0

Exponent/Logari
thm

EXP(x) Exponential function

LOG(x) Natural logarithm

LOG2(x) Logarithm with 2 as base

LOG10(x) Common logarithm

Trigonometric

SIN(x) sine

COS(x) cosine

TAN(x) tangent

CSC(x) cosecant

SEC(x) secant

COT(x) cotangent

ASIN(x) arcsine, -/2ASIN(x)/2

ACOS(x) arccosine, 0ACOS(x)

ATN(x) arctangent, -/2 < ATN(x) < /2

Angle formed by a half-line connecting the origin and point


ANGLE(x,y)
(x,y) and positive direction of x-axis, < ANGLE(x,y)

Hyperbolic

TANH(x) Hyperbolic tangent


SINH(x) Hyperbolic sine

COSH(x) Hyperbolic cosine

Random number

RND Pseudo-random, 0RND < 1

Time

TIME Time in seconds elapsed from midnight of the day

Others

PI Approximate value of

MAXNUM Largest expressible positive number

EPS(x) Difference with the number just before x or just after x

MAX(a,b) Larger one of a and b

MIN(a,b) Smaller one of a and b

Appendix 4. Difference between minimal BASIC and Full BASIC

(1) Lower bounds of array indices


The default lower bound of array indices is 0 in minimal
BASIC, though it is 1 in Full BASIC.
If index 0 is required, write
OPTION BASE 0
in the beginning of the program.

(2) Implicit array declaration


Although minimal BASIC allows arrays to be declared
implicitely,
all arrays must be declared explicitly using DIM (or DECLARE)
statements in Full BASIC.
Back

Вам также может понравиться