Sei sulla pagina 1di 67

c  c  cc 

 c c
c c

 c 
For CHEM153, 156 and 250.
In our work as S and E students and
practitioners, there comes a time when
we must reduce our statement or
statements to numbers. We therefore
must have this capability. Absent this,
our statement or statements hardly
amount to anything. CTL, 26June04.
(   (  (
 INTRODUCTION
± Use of computers at nearly all levels of
instruction
± Low cost, widespread availability
± Simply unacceptable to have
science/engineering students go through
college without doing work with computers
± While black-box approach is acceptable in
some cases, there is no substitute for
one¶s creativity and design.
± Empowerment vs canned programs
± For new comers,GWBASIC a good start-
easy to learn, portable executable program
with graphics capability, and is a freeware.
± BASIC-acronym for Beginners All-purpose
Symbolic Instruction Code
 designed as a language for beginners
 developed by John Kemeny and Kenneth Kurtz
 GWBASIC-version of BASIC produced by
Microsoft,Inc.
± Other languages:
 FORTRAN - Formula Translation; for S and E.
 Gnu Fortran 77- freeware ; FORTRAN 90 is
most recent version.
± Gwbasic, Fortran and other higher level languages
do essentially the same thing-they interpret the
program or souce code we write into a language
the machine can understand.
± Gwbasic is a program by itself. It is an interpreter,
that is, it translates our code line by line to the
computer while our program is running.
± Fortran and similar languages interpret or compile
the entire code into a machine language before
the computer can run the program.
± Will cover only those topics useful for our courses:
CHEM 153, 156 and 250.
 (   
1. PROG1 to PROG6 ± short demonstration programs
2. QDEQN ± solves quadratic equation
3. CUBICEQN ± solves cubic equation
4. SYSLINEQ ± solves system of linear equations
5. GWBNRM ± finds root of equation using the
Newton-Raphson method.
6. GWBLFT ± does linear regression/correlation
analysis; fits data set (x, y) to linear model equation
y = a + b*x.
7. BASPLOT- illustrates simple graphics application
8. Note: other programs will be distributed as needed
during the semester;others to be written by students.
 !("#$ %
10 µ Pgm: PROG1, 19 June04
20 µ This is an example of a Gwbasic pgm.
30 X=5 µthe var x is assigned the val 5.
40 Y=10
50 Z=X+Y µthe var z is assigned the val of the sum.
60 PRINT ³X=³;X
70 PRINT ³Y=³;Y
80 PRINT ³Z=X+Y=³;Z
90 END
 !("#$ &
10 µPgm: PROG2, 19June04.
20 µThis is another example.
30 INPUT ³Please enter your name:´;N$
40 PRINT ³Mr/Miss´;N$;´It is good you could attend this
lecture.´
50 END
 !("#$ '
10 µ Pgm: PROG3, 19June04
20 µ This is a spaghetti program.
30 INPUT ³X=³;X
31 GOTO 40
35 PRINT ³X<0. Stop calculation. Get undefined sqrt.´
38 END
40 IF X< 0 GOTO 35
50 µX> = 0
60 Y=1.75 - 2.25*X + X*SQR(X) + 3.05*X^3
70 PRINT ³X=³;X;TAB(20);´ Y=³;Y
80 GOTO 38
 !("#$ (
10 µPgm: PROG4, 19June04.
20 µThis is a structured program.
30 INPUT ³X=³;X
40 IF X > = 0 THEN GOTO 80
50 µX < 0
60 PRINT ³x < 0. Calcn stopped .SQR(X) undefined.´
70 GOTO 100
80 Y=1.75 -2.25*X + X*SQR(X) +3.05*X^3
90 PRINT ³X=³;X;TAB(20);´Y=³;Y
100 END
 (  )c

Will see the results of running the programs


later:
PROG1
PROG2
PROG3
PROG4
(cc ( c c*

 Beginning a session
± Gwbasic screen; KEY OFF, KEY ON
 Coding or writing a new program (NEW)
 Saving a program (SAVE or F4 key)
 Loading or recalling a program (LOAD or F3
key)
 Running a program (RUN or F2 key)
 Ending your computer session (SYSTEM)
(+#$ , ,
" + -+ (
 NEW
 SAVE ³filename´
 LOAD ³filename´
 RUN ³filename´
 SYSTEM

 Note: close quotation optional. Extension


name if not present is understood to be .BAS.
(  * c 
 A Gwbasic pgm consists of numbered
program lines: all lines are executable except
REM (or µ) lines. The lines are executed
according to numerical sequence.
 Correcting errors-key operations
 Inserting lines
 Some commands for editing:
± CLS, FILES, LIST
± RENUM, DELETE
(+#$, ,
" + -+ (
 CLS
 FILES
 LIST
 RENUM
 DELETE
 )* () .  / 
(   ( $ %
A Gwbasic program as shown in the examples is made
up of a structured collection of numbered LINE
STATEMENTS, which are executed by the computer
according to numerical sequence.
Structured means the line statements carry out specific
tasks in accordance with some clear and logical
procedure.
SYNTAX
Line number statement [ : statement ] [ µcomment ]
Note:[ ] refer to optional elements in the line statement.
 )* () .  / 
(   ( $ &
EXAMPLES OF LINE STATEMENTS
10 X = 5 : R = 8.03 : C=A*B µC is the speed in cm/sec
300 Z = 2.98*(X+1.07)
500 PRINT X, Y, Z
600 GOTO 198
89 GOSUB 345
900 LPRINT A,B,C
40 IF X<=2 THEN GOTO 30 ELSE GOTO 90
10 REM Program does linear regression analysis.
 )* () .  / 
(   ( $ '
QUESTION: What makes up a line statement? How do
we construct them?
1. NUMERIC CONSTANTS - 2, 1/4, -56.083, 0.000367,
-3.45E+12, 12.9213, 6.213453678921234
2. VARIABLES - X , Y, DIST , A(2), B(3,4), NAME$
3. OPERATIONS - arithmetic/algebraic operations: + , -,
^ , / ,\ , MOD
4. RULES - naming of variables, hierarchy of
operations, use of parentheses, ...
5. STRUCTURE - flow of control, program layout, ...
%   c c $ %
TYPES OF NUMERIC CONSTANTS
1. Integer - an ordinary integer, positive or negative.
Range -32768< x < 32768 .
Example 7, -23, 21346, +789
2. Single precision - a number with six or fewer
significant digits that has a decimal point.
Range 10^(-38) < x < 10^(+38)
(^ refers to exponentiation, meaning raised to)
Example 234.567, -9.8765, 6.023E+23
%   c c  &
3. Double precision ± a number with seven or more
significant digits and a decimal point. May have as
many as 17 significant digits.
Range As in single precision constants
Example 3.76324523, 0.9987698543574532,
1.6578438D-12
%   c c $ '
TYPE DECLARATION TAGS
The type of a number can be indicated by a type
declaration tag:
TYPE TAG EXAMPLE
1. Integer % 3%, 564%
2. Single precision ! 1.34! , 43.7865!,
23.56E-8
3. Double precision # 3.4567#, 2.67D+21
&0  ) $ %
RULES FOR NAMING OF VARIABLES
1. Characters must be alphanumeric,i.e., use
alphabetic (A-Z) and numeral (0 ± 9) characters
only.
2. First character must be a letter.
3. Variable name may contain as many as 40
characters. No blank spaces in a name.
Note: Use variable names which reflect the data stored
in the variable. Also, long variable names are not
practical or advisable to use in a program.
&0  ) $ &
Variables in Gwbasic and other programming
languages are classified according to the data they
store. We have the following types in Gwbasic:
Variable type Type declaration tag Example
1. Integer % J%, KK%, ICT%
2. Single ! X!, A7!, DIST!
3. Double # XJ23#, AREA#
4. String $ TITLE$, A5B$
5. Note: String variables in Gwbasic are initialized to
the null character ³ ³. The other variables are
initialized to 0.
&0  ) $ '
VARIABLE DECLARATION
1. Each variable must be assigned a type.
2. In general, however, it is not necessary to worry
about variable type declaration in a program.
Gwbasic adopts an implicit declaration of variables:
variable names which end with the $ tag are
declared string variables; variable names which do
not end in any tag character are declared variable
names of type SINGLE.
3. Explicit variable type declaration can be
accomplished using either the type declaration tags
(%.!,#,$) or the DEFtype statements.
&0  ) $ (
EXAMPLES ± EXPLICIT VARIABLE TYPE
DECLARATION
1. Using the tag characters ± A%, ITEM$, Y!, BBC#
2. Using the DEFtype statements ± put these
statements at the beginning of the program.
DEFINT B-F, L-M, P This means that all variable
names which begin with the letters B to F, L to M,
and P are to be treated as integer variables, that is,
the values they store are integer constants.
DEFSNG, DEFDBL, DEFSTR statements for single,
double, and string variables respectively follow the
same syntax.
Note: Tag characters override DEFtype statements.
&0  ) $ 
SUBSCRIPTED VARIABLES
The purpose is to use the same variable name to refer to
a collection of data or numbers.
Example: X(I), I = 1, 10
A(K , L ), K = 1,10 , L = 1, 25
Here , X is a one-dimensional array while A is a two-
dimensional array. The dimensions or sizes of the arrays
are communicated to the computer by using the DIM
statement:
10 DIM X(10), A(10,25)
Note:Put DIM statements at the beginning of the
program.
'  c  $ %
1. 1. Hierarchy of operations: list is of descending
priority
2. Operation Symbol Example
Exponentiation ^ 2^15, X^5,
5.12^(1/3)
Multiplication, division *, / X*Y, A/2.35
Integer division \ 3\2, 9\2
Remainder in integer MOD 8 MOD 3
division
Addition,subtraction +, - 6.7 +89.3 ± 5.7
'  c  $ &
2. Arithmetic operations are carried out LEFT to RIGHT.
3. Use parentheses whenever their use will help clarify
the order of the operations that must be carried out.
Inner parentheses are calculated first.
Examples
3.6*89.2+6^3-8.7+2.3-1.9
((2.8-3.5*6)/3.9)-(2.7/3.8+43.3)
4. Algebraic expressions are constructed using the
numeric constants,variables and the arithmetic
operations discussed above. Built-in mathematical
functions in Gwbasic enlarge the kind of algebraic
expressions we can employ in a program.
 )c$ /c  $ %

FUNCTION SYNTAX
1. Sine SIN(X) , X in radians
2. Cosine COS(X)
3. Tangent TAN(X)
4. Arc tangent ATN(X)
5. Square root SQR(X) , X >= 0
6. Exponential EXP(X)
7. Natural logarithm LOG(X) , X > 0
 )c$ /c  $ &
FUNCTION SYNTAX
8. Absolute value ABS(X)
9. Greatest integer INT(X)
less than or equal
to X
10. Remove decimal FIX(X)
part of a number
11. Remove the number SGN(X)
but keep its sign
 )c$ /c  $ '
FUNCTION SYNTAX
12. Convert X to integer constant CINT(X)
13. Convert X to single precision CSNG(X)
constant
14. Convert X to double precision CDBL(X)
constant
()
By this we mean the specific procedures that we must
use in order to correctly translate our code into a
language the computer can understand. We have
seen several of these rules.
Other rules relating to the various constructs of
Gwbasic may be found in the appropriate sections of
the manual you downloaded from the internet.
 cc
The structure for the various commands will be
discussed when we get to them. However,the structure
or layout of a Gwbasic program should look like the one
below:
10 µProgram documentation
20 µMain program
- dimension, type and user-defined function
statements
30 µSubroutines
40 µData statements
50 µEnd statement
c cc c cc $ %
The purpose of these statements is to receive data for
computer processing and to output the results generated
by the program.
Input statements
1. INPUT - gets input data from keyboard.
100 INPUT X,Y, Z, AY$
20 INPUT ³IFLAG=³; IFLAG
2. READ and DATA statements come together.
50 READ X, T, N$, H
µ
100 DATA 10.3, 25.6, ³argon´, 234.1
c cc c cc $ &
Output statements
1. PRINT - prints output to the screen.
100 PRINT A
50 PRINT TITLE$
350 PRINT TAB(5);X;TAB(15);Y
2. PRINT USING - for formatting output
120 PRINT USING ³##.###´;A
70 PRINT USING ³A= ##.### J=###´;A,J
3. LPRINT - as above, but print is transferred to the
line printer for a hardcopy.
4. LPRINT USING - as in no. 3 above.
 c ) c cc $ %
There are four control statements in Gwbasic: FOR-
NEXT, GOTO, IF-THEN, and IF-THEN-ELSE.
1. FOR-NEXT - for repetitive calculations.
Syntax
line # FOR X = X1 TO X2 [STEP X3]
line # statement 1
µ
line # statement n
line # NEXT X
Note: The default value of the increment X3 is 1 if the
optional bracketed expression is omitted.
 c ) c cc $ &
Example : FOR-NEXT statement
120 FOR J = 1 TO 50
130 K = 3*J+1
140 PRINT ³J =³;J;TAB(12);´K =³;K
150 NEXT J
-------------------------------------------------------------------
20 SUM = 0. : KF%= 12 : KL% = 32 : KDEL% = 5
30 FOR K% = KF% TO KL% STEP KDEL%
40 SUM = SUM + 2.87*CSNG(K%)^3
50 NEXT K%
 c ) c cc $ '
Example: nested FOR-NEXT statements
10 DIM A(50), B(50,20), C(50)
µ
40 FOR N = 1 TO 30 STEP 3
50 X = A(N)^2 + 3.87
60 FOR L = 1 TO 10
70 B(N, L) = A(N)*C(L) *X + COS(X)/LOG(X-1.05)
80 NEXT L
90 NEXT N
µ
 c ) c cc $ (
2. GOTO statement - for unconditional transfer of control
Syntax
line # GOTO line #
Example
120 GOTO 230
70 GOTO 10
 c ) c cc $ 
3. IF-THEN statement
Relational operators Symbol
Equal =
Less than <
Greater than >
Less than or equal to <=
Greater than or equal to >=
These operators are used in the argument of the IF
statement to determine the flow of control.
 c ) c cc $ 
Compound relational operators: AND , OR
Simple relational expression - involves a single
relational operator: A > 12, B<= 3.
Complex relational expression - involves several simple
relational expressions joined by the relational operators
AND and OR.
Examples:
(A>8) AND (C<2) This is true if both expressions are
true; false otherwise.
(A>8) OR (C<2) This is true provided one or the
other of the two expressions is true; false otherwise.
 c ) c cc $ 1
IF-THEN statement
Syntax: line # IF (X) THEN statement
The argument X is evaluated. If is true, the statement
following THEN is executed. If X is false, the
statement is ignored and control is transferred to the
next line statement.
Example
30 IF ( ICOUNT > J+3 ) THEN GOTO 250
40 PRINT ³J =³; J
µ
250 X = 3.78/CSNG(J)
 c ) c cc $ 2
4. IF-THEN-ELSE statement
Syntax: line # IF (X) THEN s1 ELSE s2
The argument X is evaluated. If is true, statement
s1 is executed. If X is false, statement s2 is instead
executed. The words IF, THEN and ELSE must
appear in the same line. This is a one-statement
command.
Example
30 IF (A<=B) THEN X=A^2 ELSE X=SQR(A+B)
40 PRINT A,B,X
 $*/ */c 
An algebraic expression that is repeatedly evaluated in
a program is better handled by defining it as a function.
These functions are called user-defined functions to
differentiate them from the built-in functions enumerated
earlier.
Syntax
line # DEF FNA(X) = X^2 +X*LOG(X+5)*SIN(X)
Usage
70 X = 23.34
80 G = FNA(X)
Note: DEF FN statements should be put at the
beginning of the program.
 c  $ %
A subroutine is by itself a complete program which
generally requires numerous statements to complete a
specific task, for example, to obtain the roots of a cubic
equation. Unlike a user-defined function which returns
only a single value, a subroutine returns one or more
values at the completion of its task.
Syntax : line # GOSUB line #
The line # following GOSUB refers to the first line number
of the subroutine. Calculations are done in the subroutine
until a RETURN statement is encountered. At this point,
control is transferred to the line number immediately
following the GOSUB statement. There may be several
RETURN statements in a subroutine as may be dictated
by the program logic.
 c  $ &
Variable names used in a subroutine should be unique
to that subroutine. For example, if the variables A is
used in the main program, its use in a subroutine can
modify its value in unintended ways. It is this problem
which we want to avoid, thus the initial statement . In
other languages, this is not a problem. Variable names
in a subroutine are strictly local to that subroutine.
Before calling or going into a subroutine, all the inputs
needed in the subroutine should be defined.
Several subroutines may be used, obviously as
required, in a given program.
 c  $ '
Example
50 GOSUB 100
60 PRINT ³Results from subroutine CUBICEQN´
70 X1=R1 : X2=R2 : X3=R3
80 PRINT ³X1=³;X1;´X2=³;X2;´X3=³;X3
µ
100 µSubroutine CUBICEQN
µ
190 R1=A : R2=B : R3=C
200 RETURN
µ
* c / ) $ %
There are two common files:
1. Program files - Gwbasic programs, excel programs
2. Data files - student data, grades, courses completed;
numerous experimental data (Temperature, B coef)
Our concern - data files which may be accessed by
distinct programs for various purposes.
Questions:
1. How do we create data files?
2. Assuming they have been created, how do we
access them?
* c / ) $ &
CREATING DATAFILES
Data that will be stored in a data file are first inputted or
read in the usual manner in a Gwbasic program. We then
create the data file using the following statement:
Syntax: line # OPEN ³filename´ FOR OUTPUT AS # N
filename - name assigned to the data file
- example: TBDATA, ABVRL.DAT
N - is a reference number assigned to the filename for
convenience. The filename need not be typed every time
we refer to the data file. Use 1 <= N <= 99.
* c / ) $ '
CREATING DATAFILES
After opening the data file, we enter the data to be
stored by using the WRITE statement:
Syntax: line # WRITE #N, V1,V2,«,VN
N - the assigned reference number to the data file
V1,V2,«,VN - list of variables the values of which are
to be stored in the data file.
After all the data had been stored into the data file, we
close the file as follows:
Syntax: line # CLOSE #N
N - the reference number
* c / ) $ (
CREATING DATAFILES - example
10 NDATA=100
µ
40 OPEN ³TBDATA´ FOR OUTPUT AS #2
50 WRITE #2, NDATA
60 FOR I=1 TO NDATA
70 WRITE #2, T(I),B(I)
80 NEXT I
µ
100 CLOSE #2
* c / ) $ 
ACCESSING DATAFILES
We access data files by using the following statements:
Syntax: line # OPEN ³filename´ FOR INPUT AS # N
line # INPUT #N, V1,V2,«,VN
line # CLOSE #N
Filename, N, and V1,«,VN refer to the same items
discussed earlier.
* c / ) $ 
ACCESSING DATAFILES - example
µ
30 OPEN ³TBDATA´ FOR INPUT AS #5
40 INPUT #5, ND
50 FOR I=1 TO ND
60 INPUT #5, TEMP(I),BC(I)
70 NEXT I
µ
100 CLOSE #5
 c (  ( $ %
PURPOSE - to copy an existing program into a program
in memory. One often needs to import programs to
avoid having to retype them. We accomplish this by
using the following commands:
RENUM -to avoid overriding the line numbers and
hence statements of the program in memory.
SAVE - option A is required in order to properly carry out
the MERGE command.
Syntax: line # SAVE ³filename´,A
MERGE - after the program to be imported had been
saved with the A option, it may then be merged with the
program in memory using the following statement:
Syntax: line # MERGE ³filename´
 c (  ( $ &
Example
10 µPgm A | 10 µPgm B
20 PRINT ³PgmA - 1´ | 20 PRINT ³PGM B-1´
30 PRINT ³PgmA - 2´ | 30 PRINT ³PGM B-2´
40 PRINT ³PgmA - 3´ | 40 PRINT ³PGM B-3´
50 END | 50 PRINT ³PGM B-4´
| 60 PRINT ³PGM B-5´
| 70 END
Assume PgmA is in memory. If we merge PgmB with it,
the latter¶s lines 10 to 50 will override similar lines in
PgmA. To avoid this we renumber the lines in PgmB.
 c (  ( $ '
Example - continue
We load PgmB so it is in memory. We renumber, for
example, by using RENUM 200,10. PgmB will then have
200 as its first line number. The others follow in increments
of 10.
We then save PgmB as follows: SAVE ³PGMB´,A
We then load PgmA: LOAD ³PGMA´
With PgmA in memory, we can execute the merge
statement to import PgmB: MERGE ³PGMB´
 c (  ( $ (
Example - result of merging; do appropriate editing.
10 µPgm A
20 PRINT ³PgmA - 1´
µ
50 END
200 µPgm B
210 PRINT ³PGM B-1´
220 PRINT ³PGM B-2´
µ
260 END
( 
 $ %
Example -we want Gwbasic graphics capability primarily
for plotting functions. See program BASPLOT.BAS.
Commands needed:
1. SCREEN
2. COLOR
3. WINDOW
4. LINE
5. PSET
( 
 $ &
1. SCREEN - There are several screen modes:
Screen mode Description
0 text mode (25 rows,40-80 columns)
1 medium-resolution graphics (200 rows,
with 320 rectangles per row; 4 colors)
2 high-resolution graphics (200 rows,
with 640 rows per row; 2 colors-black
and white)
Syntax: line # SCREEN N
N is either 1 or 2. Use 1.
( 
 $ '
2. COLOR
To use colors in our plots, we must first activate the color
capability using the following statement:
Syntax: line # SCREEN 1,0
1 refers to the medium-resolution mode
0 means the color option is on; use 1
instead if the color option is to be
deactivated.
Syntax: line # COLOR K, L
K is a number from 0 to 15 for background
color; L is either 0 or 1 for foreground color.
( 
 $ (
Background colors
K
0 - black 9 - light blue
1 - blue 10 - light green
3 - cyan 11 - light cyan
4 - red 12 - light red
5 - magenta 13 - light magenta
6 - brown 14 - yellow
7 - white 15 - high intensity white
8 - gray
( 
 $ 
Foreground colors
Palette L=0 Palette L=1
0 - same as background 0 - background
1 - green 1 - cyan
2 - red 2 - magenta
3 - brown 3 - white
( 
 $ 
3. WINDOW
The WINDOW statement allows one to define his or
her own coordinate system on the screen.
Syntax: line # WINDOW (X1,Y1) - (X2,Y2)
The coordinates refer to the coordinates of two
opposite corners, connected by the diagonal, of a
rectangle.
Example: 20 WINDOW (-2, 5) - (5,-3)
( 
 $ 1
4. LINE
Syntax: line # LINE (X1,Y1) - (X2,Y2)
Use this statement to draw lines connecting
the two points, for example, to draw the
axes and the tick marks along the axes.
Example: 50 LINE (-2,0) - (10,20)
60 LINE (0,5) - (0,-5)
( 
 $ 2
5. PSET - To illuminate pixels corresponding to the
points (x,y) along a curve, the PSET statement is used.
Syntax: line # PSET (X,Y), J
(X,Y) is the coordinate that is illuminated.
J refers to the color of the chosen palette L
indicated in the statement COLOR K, L.
Example:
100 FOR X = 1. To 12.5 STEP .01
110 Y = X*COS(X - 2.5)
120 PSET (X,Y),2
130 NEXT X
 (   3,
 #
1. PROG1 to PROG6 ± short demonstration programs
2. QDEQN ± solves quadratic equation
3. CUBICEQN ± solves cubic equation
4. SYSLINEQ ± solves system of linear equations
5. GWBNRM ± finds root of equation using the
Newton-Raphson method.
6. GWBLFT ± does linear regression/correlation
analysis; fits data set (x, y) to linear model equation
y = a + b*x.
7. BASPLOT- illustrates simple graphics application
, + 
1, We have discussed some aspects of Gwbasic
programming which are useful in CHEM 153, 156 and
250.
2. As you develop programming skills, you will find other
languages, FORTRAN, in particular, easy to learn.
3. Meanwhile, learn as much as you can from the
programs that were distributed. Copy the programs into
your diskettes for use in our courses.
4. We did not discuss flowcharts, but you can study this
on your own.
/  ) c
The following notes are worth keeping in mind:
1. Avoid mixed arithmetic unless the same is
necessary. For all our course work, we will only need
single precision calculations.
2. Always keep one or two backup copies of your
programs.
3. Print the name of the program you are currently
working with on the screen at the beginning and at the
end of your Gwbasic program.
This ends this ppt presentation. Meanwhile let us look
at some of the programs distributed earlier.
C. T. Llaguno, 26June04.

Potrebbero piacerti anche