Basic PRG Handout Mod
Basic PRG Handout Mod
1
Kurtz was developing his Time Sharing System. They both recognized that the new
language should meet the following specifications:
1) General purpose 2) Ease of use 3) Expandable 4) Interactive 5) with debugging help 6)
efficient 7) hardware independent 8) OS independent.
To obtain all this they started from FORTRAN and ALGOL, taking from them the general
structure and the English words. Program lines were numbered both because as such the
flow of the program was unequivocally determined, and because it helped simplify editing
(rows could be deleted just writing the line number or changed by writing a new line with
the same number). The final version of what was called “Dartmouth BASIC” had 14
instructions. Limitations were present because programs should contain only one instruction
per row and every row should start with a command, but the “Dartmouth BASIC” was
compiled and rather fast for that time.
The efforts of Kemeney and Kurtz were repaid on May 1, 1964 when, at 4:00 am, two
BASIC programs ran simultaneously on the General Electric 225 mainframe at Dartmouth
College.
2
The first generation languages, or 1GL, are low-level languages that are machine
language.
The second generation languages, or 2GL, are also low-level languages that
generally consist of assembly languages.
The third generation languages, or 3GL, are high-level languages such as C,BASIC.
The fourth generation languages, or 4GL, are languages that consist of statements
similar to statements in a human language. Fourth generation languages are
commonly used in database programming and scripts.
The fifth generation languages, or 5GL, are programming languages that contain
visual tools to help develop a program. A good example of a fifth generation
language is Visual Basic.
TYPES OF PROGRAMMING LANGUAGE
There are three types of programming language:
Machine language (Low-level language)
Assembly language (Low-level language)
High-level language
Low-level languages are closer to the language used by a computer, while high-level
languages are closer to human languages.
Machine Language
• Machine language is a collection of binary digits or bits that the computer reads and
interprets.
• Machine languages are the only languages understood by computers.
• While easily understood by computers, machine languages are almost impossible for
humans to use because they consist entirely of numbers.
Assembly Language
• A program written in assembly language consists of a series of instructions mnemonics
that correspond to a stream of executable instructions, when translated by an assembler that
can be loaded into memory and executed.
• Assembly languages use keywords and symbols, much like English, to form a
programming language but at the same time introduce a new problem.
3
The problem is that the computer doesn't understand the assembly code, so we need a way to
convert it to machine code, which the computer does understand.
• Assembly language programs are translated into machine language by a program called an
assembler.
Example: –
Machine language: 10110000 01100001
Assembly language: mov a1, #061h
Meaning: Move the hexadecimal value 61 (97 decimal) into the processor register named
"a1".
High Level Language
• High-level languages allow us to write computer code using instructions resembling
everyday spoken language (for example: print, if, while) which are then translated into
machine language to be executed.
• Programs written in a high-level language need to be translated into machine language
before they can be executed.
• Some programming languages use a compiler to perform this translation and others use an
interpreter.
Examples of High-level Language: ADA, C, C++, JAVA, BASIC, COBOL, PASCAL,
PHYTON.
PURPOSE OF PROGRAMMING
speed up the attainment of answers whose solution process is already known so that
the time can be used for more valuable things
automate tedious tasks whose methods are already known so that the time can be
used for more valuable things
accelerate communications, used in concert with other technologies to speed up and
automate the processes that enable said communications, improving the efficiency of
communications so that the time can be used for more valuable things
create tools which, used singly or in combination, enable permutations of the above,
so that the time can be used for more valuable things
4
using the speed and automation mentioned above, create abstract environments
(frameworks) to enable better understanding, discovery of relationships, and ...
well ... entertainment (games and the like).
MEANING OF BASIC
B-----Beginners
A-----All-purpose
S------Symbolic
I------Instruction
C-----Code
Flow Charts
Flow charts are drawing diagrams to illustrate series of steps the program must follow to
obtain result or the outputs. The following the figures used in flow charts:
Decision symbol .
Preparative symbol
5
Link symbol
Direction traffic
6
MODULE TWO
DATA TYPE IN BASIC
1. INTEGERS AND LONG INTEGERS: Integers are stored as 16-bit binary numbers
(two bytes) ranging in value from -32,768 to + 32,767. “Long” integers are stored as
signed 32-bit binary numbers ranging from -2,147,483,648 to + 2,147,483,647.
2. STRINGS: there are mixture of various characters to form words. Strings can include
some acceptable symbols.
3. FLOATING POINT NUMBERS: these values are represented in a different format
from integers. Each floating point value consists of three parts: the sign, the
exponent, and the mantissa.
Strings
There are certain types of data (or information) called "strings." Strings contain a sequence
of characters (letters, numbers, and symbols) enclosed in quotation marks. For example,
"Hello
World!" is a string. These are also examples of strings
"0123456789" , "This is a string" , "abc123" , "1 + 1 = 2" , "!@#$%^&*()" .
BASIC CHARACTER SETS
The following characters are used by QBASIC System:
1. Letters of the alphabet (A, B, C,……….Z).
2. Digit Numbers (0, 1, 2………………..9).
3. Characters and Symbols( +,-,*, /, =,^, ( ),<,> , >=,=< ,<>,@,#,!,?,",% ).
4. Special Words ( go to, if , read, print, input).
BASIC VARIABLES
A variable is a piece of data kept in the computer's memory (RAM). The location of a
variable in RAM is called the "address." You can equally say a variable is a container for
holding data in memory. There are two categories of Variables in BASIC: Numeric & String
1. Numeric Variables: These are used variables used to hold a number in integer, real or
exponent form. There are 286 numeric variable names allowed by STANDARD BASIC.
7
The single letters A,B,C,……..Z and combinations of any single letter followed by any
single number A0,A1,…….A9, B0,B1,…..Z0,……Z9.
2. String Variables: These are used to hold a string of any characters or textual data. There
are 26 such variables. It is represented by any alphabet followed by a dollar $ sign such as
(A$, BC$, A2$, ZW$). A character string is differentiated from a numeric data by enclosing
the string in quotation marks. Examples are “A”, “23”, “Esther Hassan”, A$ =” JOY
MODIBBO”
BASIC variable name may contain up to 40 characters. The characters allowed in a variable
name are letters, numbers, the period (.), and the type-declaration characters (%,&,!,#,$).
Follow these guidelines when naming a variable:
1. The first character in a variable name must be a letter.
2. A variable name must not be a reserved word.
3. Variable names cannot duplicate procedure names and symbolic constant names.
Constants in BASIC
Constants in BASIC are divided into two types:
1. Numeric Constants: There are two types of numeric constants:
• Real: the numbers used may be written in decimal form such as (6.9,-52.76, 0.095, -
3269.0)
• Integer: Whole numbers may be written without the decimal point such as (89,-132,7698)
• Exponential Form: This form requires a number followed by the letter E, such as (2.8E05,
0.57E-03, 0.07E-9, and 29.8E7).
2. String Constants. A string consists of a sequence of characters (letters, numbers, and
symbols) enclosed in double quote marks. Strings usually consist of names or address or
cities such as "Computer", "Ikeja".
BOOLEAN DATA
The Boolean data type can only represent two values: true or false. Typically, a 1 is used to
represent True, and a 0 is used to represent False. Consider the following example where a
user inputs two values and the program determines whether the first one is smaller than the
second one or not.
8
x=8
y=7
In this example the first value is in fact not smaller than the second one, and the program
therefore results in a Boolean value of False. The Boolean type is the primary results of
conditional statements, which are used to control workflow in program. For example, if a
particular condition is true, then do this - if the condition is false, then do something else
9
division and vice versa because they have the same hierarchy. The last of all is addition and
subtraction.
Thus the expression 9*5+6 is the same as (9*5) +7 because multiplication will be performed
before addition.
RELATIONAL OPERATORS
They can be used to compare two values. The result of which is either true or false.
They are:
1. = equal to
2. < less than
3. > greater than
4. < = Less than or equal to
5. > = greater than or equal to
6. < > Not equal to
Examples of usage are:
A> B , A < > C A= B etc.
A < > B THEN A < B ELSE A > B
Logical operators are AND, OR, NOT.
They perform tests on multiple relations or Boolean operators.
For example, IF D <200 AND F >5 THEN 70
IF I <10 OR K >0 THEN 40
IF NOT P THEN 100
FUNCTIONS
Functions differ from commands and statements in that they cannot be performed by
themselves. They must be used in conjunction with either a statement or a command. If
used with an assignment statement (=) the function must appear on the right hand side of
the = sign.
FUNCTION MEANING
SIN(x) The sine of x
COS(x) The Cosine of x
TAN(x) The tangent of x
10
ATN(x) The arctangent of x
EXP(x) The value of e x
LOG(x) The natural logarithm of x
SQR(x) The square root of x
INT(x) The largest integer not greater than x
ABS(x) The absolute value of x
SPC(x) Leave x spaces
SGN(x) The sign of x: 1 if x > 0, 0 if x= 0, -1 if x < 0
TAB(x) Start printing at position x+1
The quantity x is called the argument or parameter of the function. Any of these functions
can be used in a BASIC program. However, a programmer can define his own functions to
simplify a BASIC program.
PUNCTUATION MARKS
Those available in BASIC are
. decimal
, comma
: colon
; semi-colon
“ Quotation mark
These elements are elements of standard BASIC. Some other versions of BASIC include
some enhancements to make the language more versatile and powerful.
11
MODULE THREE
BASIC STATEMENT (INPUT /OUTPUT STATEMENT)
The REM Statement
The general form of the REMARK statement is:
REM [remark] where remark may be any remark the programmer chooses to make to
describe the program, to identify various parts of program, or even to serve as a blank line
between parts of the program. For example:
REM this program is named calculate Rem program written in 2016-08-23
Rem input modul
Rem output modul
Print Statement
The general form of the Print statement is:
Print expression (, or ;) expression etc. Where expression is any number, any string of
words, any variable, or any combination of numbers and variables in an algebraic
expression. Commas or semicolons must be used to separate expressions. For example:
Print
Print X
Print a,b,c
Print s;t;u;r;v
Print "the sum is";s9
Print a$,B$,c$
Input Instructions There are three types of input instructions include:
1. Let statement.
2. Input statement.
3. Read / Data statement.
Let statement. The general form of the Let statement is:
Let variable = expression Where variable may be either a numeric variable or a string
variable and expression may be either an arithmetic expression or a string expression.
Strings cannot be placed into numeric variables, or vice versa. The following are examples
of let statement:
12
Let X=25
Let A$="computer"
Let R3=5*x*(X-9)
Let M$=N$
INPUT STATEMENT
One way to receive input from the keyboard is with the INPUT command. The INPUT
command allows the user to enter either a string or a number, which is then stored in a
variable.
INPUT data$
PRINT data$
When this program is executed, the INPUT command displays a question mark, followed by
a blinking cursor. And when you enter text, the program stores that text into the variable
data$, which is printed to the screen.
To receive a number, use a non-string variable.
INPUT number
PRINT number
Labels and the GOTO and GOSUB commands
The GOTO and GOSUB commands enables you to jump to certain positions in your
program.
Labels are used to specify what point in the program to continue execution.
GOTO
To use GOTO, place a label somewhere in your program, and then enter.
GOTO <label>
Run the following example program:
PRINT "1"
GOTO TheLabel
PRINT "2"
TheLabel:
PRINT "3"
Output (notice how PRINT "2" is skipped):
1
13
3
GOSUB
The GOSUB command is the same as GOTO, except when it encounters a RETURN
statement, the program "returns" back to the GOSUB command. In other words, RETURN
continues program execution immediately after the previous GOSUB statement.
PRINT "1"
GOSUB TheLabel
PRINT "2"
END
TheLabel:
PRINT "3"
RETURN
(Note: The END command exits the program.)
Since the program returns to the GOSUB command, the number 2 is printed this time.
1
3
2
Line numbers
"Line numbers" can be used as labels.
PRINT "1"
GOTO 10
PRINT "2"
10 PRINT "3" (Notice the line number)
You can also write the program like this:
10 PRINT "1"
20 GOTO 40
30 PRINT "2"
40 PRINT "3"
The line numbers don't even have to be in sequence.
17 PRINT "1"
2 GOTO 160
14
701 PRINT "2"
160 PRINT "3"
Each of these programs output:
1
3
The Termination Statements STOP and END
The last BASIC statement in a BASIC program should always be the END statement. For
this reason, the END statement should always have the highest line number in your program.
If you type BASIC statements after the END statement, these will not be processed by
BASIC.
The STOP statement tells BASIC where in your program you want to stop processing
instructions. The general form of termination statements are;
Line number STOP
Line number END
Any program can be written without a STOP statement.
15
MODULE FOUR
CONTROL STATEMENT
Loops
"Loops" make it easier to do an action multiple times. There are at least four types of loops:
IF...GOTO, WHILE...WEND, DO...LOOP, and FOR...NEXT, IF …THEN..ELSE
IF...GOTO
This program uses IF...GOTO to create a loop:
x = 10
start:
PRINT x
x = x + 1 (This adds 1 to x)
IF x < 15 THEN GOTO start
Output:
10
11
12
13
14
WHILE...WEND
The WHILE...WEND commands continue a loop until a specified expression is false.
To use WHILE...WEND:
1. Place an expression after WHILE
2. Enter a list of commands
3. Place WEND at the end
Run the following:
x = 10
WHILE x < 15
PRINT x
x=x+1
WEND
Output (same as in previous example):
16
10
11
12
13
14
DO...LOOP
DO...LOOP is exactly the same as WHILE...WEND, except it has at least two slight
advantages.
With DO...LOOP you can:
1. Loop until an expression is true
2. Loop at least one time regardless of whether the expression is true or not.
To use DO...LOOP:
1. Specify whether the loop continues "while" the expression is true or "until" the expression
is true, using the WHILE and UNTIL statements, respectively.
2. Place an expression after WHILE/UNTIL
3. Enter a list of commands
4. Place LOOP at the end
The following uses the WHILE statement:
x = 10
DO WHILE x < 15
PRINT x
x=x+1
LOOP
This program uses the UNTIL statement:
x = 10
DO UNTIL x = 15
PRINT x
x=x+1
LOOP
They both output:
10
17
11
12
13
14
If you place the expression at the end of the loop instead, the program goes through the loop
at least once.
x = 32
DO
PRINT x
x=x+1
LOOP WHILE x < 5
This is the output because the loop was only gone through one time:
32
FOR...NEXT
FOR...NEXT provides an easier way to create a loop.
FOR x = 1 TO 5
PRINT x
NEXT x
Output:
1
2
3
4
5
NB: The x after NEXT is optional (unless you have a loop within a loop).
Also, you can use the STEP attribute to specify how much X will be increased each time
through the loop.
FOR x = 1 TO 5 STEP 2
PRINT x
NEXT x
Output:
18
1
3
5
STOPPING LOOPS
To stop a loop prematurely, use the EXIT command, followed by either FOR or DO.
FOR x = 1 TO 5
PRINT x
IF (x = 3) THEN EXIT FOR
NEXT x
Output:
1
2
3
(NOTE: This command only works with the DO...LOOP and FOR...NEXT commands, not
with WHILE...WEND or IF...GOTO.)
19
MODULE FIVE
BASIC COMMANDS
Program File Commands
SAVE filename[,a][,p]
Writes to a location the program currently residing in memory.
LOAD filename[,r]
Loads the program from a location into memory. LOAD deletes the current contents of
memory and closes all files before loading the program.
RUN filename[,r]
Loads the program from a location into memory and runs it immediately. RUN deletes the
current contents of memory and closes all files before loading the program.
MERGE filename
Loads the program from a location into memory, but does not delete the current program
already in memory.
KILL filename
Deletes the file from a location. This command can also be used with data files.
NAME old filename AS new filename
Changes the name of a location file. Only the name of the file is changed. The file is not
modified, and it remains in the same space and position on the disk. This command can also
be used with data files.
OPEN
The OPEN command is used to open files - that is, it makes files available so that Basic can
read or write to them. The general form of the command is
OPEN "filename" FOR mode AS #filenumber .
In place of filename you write the name of the file, including the directory address - some
examples of names of files are
A:\primes.bas C:\math\homework\sols.wrk
H:\roots.bas divisors.dat .
It is best to use the extension "bas" if you want your file to be easy to find; doing so ensures
the file will be listed in the "Open Program" list when you click "File - Open" in Basic. If
20
you do not include the directory address, as in the last example, Basic will assume that the
file is located in the same directory as the main Basic program.
In place of mode you write one of the three modes - these are OUTPUT, APPEND, and
INPUT. The OUTPUT mode permits Basic to write information to the file. If the file already
exists, Basic will overwrite the old file with the new information, destroying all previous
contents of the file. If the file does not already exist, Basic will create a file with that name.
The APPEND mode allows Basic to write information to the file without destroying the old
information - Basic just adds the new information onto the end of the file. Again, if the file
does not already exist, Basic will create it. Finally, the INPUT mode permits Basic to read
information from the file, such as it would from a DATA statement. If the file does not exist,
Basic stops and gives an error message.
In place of filenumber you write a number for the file (an integer between 1 and 255). In
subsequent Basic statements you use this number when referring to the file. It is possible to
have several files open at once, but each must have a different file number. Here are some
examples of OPEN statements:
OPEN "A:\primes.bas" FOR OUTPUT AS #1
OPEN "H:\divisors.bas" FOR APPEND AS #6
OPEN "C:\math\homework\sols.bas" FOR INPUT AS #143 .
These three statements allow Basic to overwrite the file "primes", to make additions to the
file "divisors", and to read from the file "sols".
CLOSE
The CLOSE command is used to close one or more files - examples are
CLOSE #5 CLOSE #5, 7 CLOSE
The first of these commands closes the file numbered 5, while the second closes the two
files numbered 5 and 7. The third CLOSE command, followed by no number,
closes all files. In order to avoid possible memory problems and to increase efficiency, it is
prudent to close a file after a program is finished with it.
PRINT #
The PRINT # command writes data to a file - the data is written to the file whose number
follows "#". The command works like the PRINT command, except that the information is
sent to the file instead of printed to the screen. The statement
21
PRINT #7, "The solution of the equation is"; X
writes to file # 7 the information listed. Of course a file must be opened before anything can
be written to it - so always an OPEN command must precede a PRINT # command. If file #
7 were opened in OUTPUT mode, the information overwrites the file, but if it were opened
in APPEND mode the information is added to the end of the file. Note that, in contrast to the
ordinary PRINT for printing to the screen, PRINT #7 is followed immediately by a comma
before the printing instructions.
Example :
The following sequence opens a file on the A drive, writes to the file the even numbers from
2 to 10 separated by commas, and then closes the file:
OPEN "A:\evens.bas" FOR OUTPUT AS #1
PRINT #1, "The even numbers from 2 to 10 are:"
FOR I = 2 TO 10 STEP 2
PRINT #1, I; " , ";
NEXT I
CLOSE #1
You can also combine USING with the PRINT # statement, as in
PRINT #3, USING "The principal is $$#####.##"; P .
WRITE #
The command WRITE # works a lot like PRINT #, sending data to a file. However, WRITE
# sends data in a format which can be read later by Basic - it separates items by commas and
puts quotation marks around strings, much as you would in typing a DATA statement for
Basic to access with a READ statement. This command is useful in programs that process
information input by the user, or that generate data that might be read by Basic at some later
date. An example of use of this command is
WRITE #4, "John Smith", 23, "1423 Maple Street", "Topeka, Kansas" .
As there is not much use for this command in most mathematical programming, we will not
discuss it in detail.
INPUT #
The INPUT # command reads from a file data that has been written by Basic with the
WRITE # command. It works pretty much like the READ command, except that data is read
22
from a file instead of from a DATA statement. Data from the file is read in sequential order,
as from DATA statements. An example of use of this command is
INPUT #4, fullname$, age, address$, city$ .
The file must first be opened in INPUT mode before this command can be used. Again, as
the INPUT # command is seldom needed in mathematical programming, we will not discuss
it in detail.
EOF (End of File)
Often when reading data from a file a program does not know beforehand the length of the
file. If the reading is done from within a loop, there must be a way to stop the loop when all
the data is read - otherwise, Basic produces an error message when asked to read more data
after the end of the file has been reached. For this purpose Basic employs a function EOF(),
that checks whether the last reading of the file used up all the data in the file. Here are
examples of the use of this function :
1) S=0 2) S=0
DO UNTIL EOF(3) DO
INPUT # 3, X INPUT # 3, X
S=S+X S=S+X
LOOP LOOP UNTIL EOF(3)
PRINT "THE SUM IS "; S PRINT "THE SUM IS "; S
Each of the loops reads numbers from the file assigned number 3, and adds these numbers to
calculate the sum of all numbers in the file. The function EOF(3) checks whether the end of
the file numbered 3 has been reached - if that is the case the program jumps out of the loop
to the next command after the loop. On the left above the check is done at the top of the
loop, and on the right it is done at the bottom. The sum is the same in the two cases, and
after each loop this sum is printed to the screen.
SLEEP: Sleep makes the program wait for the user to press a key
The general format is SLEEP
LOF (Length of File): This returns the length (number of bytes) allocated to the file
The general format is LOF (file number) file number is number of the file that the file was
open under.
STRUCTURED DATA, ARRAYS AND THE USE OF DIM STATEMENT
23
An array is a group of objects referenced with the same variable name. The individual
values in an array are called elements. Array elements are also variables and can be used in
any BASIC statement or function that uses variables. The word DIM is used to declare the
name, type and number of elements in the array. Each element in an array is referred to by
an array variable subscripted with an integer or integer expression.
DIM name(75) as STRING
The above statement is declaring an array “name” with space for 75 variables and the only
data type to be inserted into the array must be a STRING. To insert a value space number 1:
name(1) = “John Ishaya”
The word DIM can also be used to fix a type on a particular variable, for example:
DIM score AS INTEGER
It implies the variable “score” is now of the type INTEGER, thus cannot accept another data
type.
MODULE SIX
DATA FILES, SEQUENTIAL INPUT AND OUTPUT FILES, RANDOM FILES
We are going to discuss two types of data files:
Sequential files
Random access files
24
Sequential files are easier to create than random access files, but are limited in flexibility
and speed when accessing data. Data written to a sequential file is a series of ASCII
characters. Data is stored, one item after another (sequentially), in the order sent. Data is
read back in the same way.
Creating and accessing random access files requires more program steps than sequential
files, but random files require less room on the disk, because BASIC stores them in a
compressed format in the form of a string.
The following sections discuss how to create and use these two types of data files.
Creating a Sequential File
The following statements and functions are used with sequential files:
CLOSE LOF
EOF OPEN
INPUT# PRINT#
LINE
PRINT# USING
INPUT#
LOC UNLOCK
LOCK WRITE#
The following program steps are required to create a sequential file and access the data in
the file:
1. Open the file in output (O) mode. The current program will use this file first for
output:
OPEN "O",#1,"filename"
2. Write data to the file using the PRINT# or WRITE# statement:
3. PRINT#1,A$
4. PRINT#1,B$
PRINT#1,C$
5. To access the data in the file, you must close the file and reopen it in input (I) mode:
6. CLOSE #1
OPEN "I",#1,"filename
25
7. Use the INPUT# or LINE INPUT# statement to read data from the sequential file
into the program:
INPUT#1,X$,Y$,Z$
Example 1 is a short program that creates a sequential file, data, from information input at
the terminal.
Example 1
10 OPEN "O",#1,"DATA"
20 INPUT "NAME";N$
30 IF N$="DONE" THEN END
40 INPUT "DEPARTMENT";D$
50 INPUT "DATE HIRED";H$
60 PRINT#1,N$;","D$",";H$
70 PRINT:GOTO 20
RUN
NAME? JOY MOUSE
DEPARTMENT? AUDIO/VISUAL AIDS
DATE HIRED? 01/12/72
NAME? ESTHER HOLMES
DEPARTMENT? RESEARCH
DATE HIRED? 12/03/65
NAME? HASSAN SCROOGE
DEPARTMENT? ACCOUNTING
DATE HIRED? 04/27/78
NAME? SUPER MANN
DEPARTMENT? MAINTENANCE
DATE HIRED? 08/16/78
NAME? DONE
OK
Accessing a Sequential File
The program in Example 2 accesses the file data, created in the program in Example 1, and
displays the name of everyone hired in 1978.
26
Example 2
10 OPEN "I",#1,"DATA"
20 INPUT#1,N$,D$,H$
30 IF RIGHT$(H$,2)="78" THEN PRINT N$
40 GOTO 20
50 CLOSE #1
RUN
HASSAN SCROOGE
SUPER MANN
Input past end in 20
Ok
The program in Example 2 reads, sequentially, every item in the file. When all the data has
been read, line 20 causes an "Input past end" error. To avoid this error, insert line 15, which
uses the EOF function to test for end of file:
15 IF EOF(1) THEN END and change line 40 to GOTO 15.
A program that creates a sequential file can also write formatted data to the diskette with
the PRINT# USING statement. For example, the following statement could be used to write
numeric data to diskette without explicit delimiters:
PRINT#1, USING"####.##,"; A, B, C, D
The comma at the end of the format string serves to separate the items in the disk file.
The LOC function, when used with a sequential file, returns the number of 128-byte records
that have been written to or read from the file since it was opened.
Adding Data to a Sequential File
When a sequential file is opened in O mode, the current contents are destroyed. To add data
to an existing file without destroying its contents, open the file in append (A) mode.
The program in Example 3 can be used to create, or to add onto a file called names. This
program illustrates the use of LINE INPUT. LINE INPUT will read in characters until it
sees a carriage return indicator, or until it has read 255 characters. It does not stop at
quotation marks or commas.
Example 3
10 ON ERROR GOTO 2000
27
20 OPEN "A", #1, "NAMES"
110 REM ADD NEW ENTRIES TO FILE
120 INPUT "NAME"; N$
130 IF N$="" THEN 200 `CARRIAGE RETURN EXITS INPUT LOOP
140 LINE INPUT "ADDRESS? "; A$
150 LINE INPUT "BIRTHDAY? "; B$
160 PRINT#1, N$
170 PRINT#1, A$
180 PRINT#1, B$
190 PRINT: GOTO 120
200 CLOSE #1
2000 ON ERROR GOTO 0
In lines 10 and 2000 the ON ERROR GOTO statement is being used. This statement enables
error trapping and specifies the first line (2000) of the error handling subroutine. Line 10
enables the error handling routine. Line 2000 disables the error handling routine and is the
point where BASIC branches to print the error messages.
Random Access Files
Information in random access files is stored and accessed in distinct, numbered units
called records. Since the information is called by number, the data can be called from any
disk location; the program needn't read the entire disk, as when seeking sequential files, to
locate data. GW-BASIC supports large random files. The maximum logical record number
is 232 -1.
The following statements and functions are used with random files:
CLOSE FIELD MKI$
ET MKD$
28
Creating a Random Access File
The following program steps are required to create a random data file:
1. Open the file for random access (R) mode. The following example specifies a record
length of 32 bytes. If the record length is omitted, the default is 128 bytes.
OPEN "R", #1, "filename", 32
2. Use the FIELD statement to allocate space in the random buffer for the variables that
will be written to the random file:
FIELD#1, 20 AS N$, 4 AS A$, 8 AS P$
In this example, the first 20 positions (bytes) in the random file buffer are allocated to the
string variable N$. The next 4 positions are allocated to A$; the next 8 to P$.
3. Use LSET or RSET to move the data into the random buffer fields in left- or right-
justified format (L=left SET;R=right SET). Numeric values must be made into
strings when placed in the buffer. MKI$ converts an integer value into a
string; MKS$ converts a single-precision value, and MKD$ converts a double-
precision value.
4. LSET N$=X$
5. LSET A$=MKS$(AMT)
LSET P$=TEL$
6. Write the data from the buffer to the diskette using the PUT statement:
PUT #1, CODE%
The program in Example 4 takes information keyed as input at the terminal and writes it to a
random access data file. Each time the PUT statement is executed, a record is written to the
file. In the example, the 2-digit CODE% input in line 30 becomes the record number.
Example 4
10 OPEN "R", #1, "INFOFILE", 32
20 FIELD#1, 20 AS N$, 4 AS A$, 8 AS P$
30 INPUT "2-DIGIT CODE"; CODE%
40 INPUT "NAME"; X$
50 INPUT "AMOUNT"; AMT
60 INPUT "PHONE"; TEL$: PRINT
70 LSET N$=X$
29
80 LSET A$=MKS$(AMT)
90 LSET P$=TEL$
100 PUT #1, CODE%
110 GOTO 30
Accessing a Random Access File
The following program steps are required to access a random file:
1. Open the file in R mode:
OPEN "R", #1, "filename", 32
2. Use the FIELD statement to allocate space in the random buffer for the variables that
will be read from the file:
FIELD, #1, 20 AS N$, 4 AS A$, 8 AS P$
In this example, the first 20 positions (bytes) in the random file buffer are allocated to the
string variable N$. The next 4 positions are allocated to A$; the next 8 to P$.
Note
In a program that performs both INPUT and OUTPUT on the same random file, you
can often use just one OPEN statement and one FIELD statement.
1. Use the GET statement to move the desired record into the random buffer.
GET #1, CODE%
The data in the buffer can now be accessed by the program.
2. Convert numeric values back to numbers using the convert functions: CVI for
integers, CVS for single-precision values, and CVD for double-precision values.
3. PRINT N$
4. PRINT CVS(A$)
The program in Example 5 accesses the random file, infofile, that was created in Example 4.
By inputting the 3-digit code, the information associated with that code is read from the file
and displayed.
Example 5
10 OPEN "R",#1,"INFOFILE",32
20 FIELD #1, 20 AS N$, 4 AS A$, 8 AS P$
30 INPUT "2-DIGIT CODE";CODE%
30
40 GET #1, CODE%
50 PRINT N$
60 PRINT USING "$$###.##";CVS(A$)
70 PRINT P$:PRINT
80 GOTO 30
With random files, the LOC function returns the current record number. The current record
number is the last record number used in a GET or PUT statement. For example, the
following line ends program execution if the current record number in file#1 is higher than
99:
IF LOC(1)>99 THEN END
Example 6 is an inventory program that illustrates random file access. In this program, the
record number is used as the part number, and it is assumed that the inventory will contain
no more than 100 different part numbers.
Lines 900-960 initialize the data file by writing CHR$(255) as the first character of each
record. This is used later (line 270 and line 500) to determine whether an entry already exists
for that part number.
Lines 130-220 display the different inventory functions that the program performs. When
you type in the desired function number, line 230 branches to the appropriate subroutine.
Example 6
120 OPEN"R",#1,"INVEN.DAT",39
125 FIELD#1,1 AS F$,30 AS D$, 2 AS Q$,2 AS R$,4 AS P$
130 PRINT:PRINT "FUNCTIONS:":PRINT
135 PRINT 1,"INITIALIZE FILE"
140 PRINT 2,"CREATE A NEW ENTRY"
150 PRINT 3,"DISPLAY INVENTORY FOR ONE PART"
160 PRINT 4,"ADD TO STOCK"
170 PRINT 5,"SUBTRACT FROM STOCK"
180 PRINT 6,"DISPLAY ALL ITEMS BELOW REORDER LEVEL"
220 PRINT:PRINT:INPUT"FUNCTION";FUNCTION
225 IF (FUNCTION<1)OR(FUNCTION>6) THEN PRINT "BAD FUNCTION
NUMBER":GOTO 130
31
230 ON FUNCTION GOSUB 900,250,390,480,560,680
240 GOTO 220
250 REM BUILD NEW ENTRY
260 GOSUB 840
270 IF ASC(F$) < > 255 THEN INPUT"OVERWRITE";A$: IF A$ < > "Y" THEN
RETURN
280 LSET F$=CHR$(0)
290 INPUT "DESCRIPTION";DESC$
300 LSET D$=DESC$
310 INPUT "QUANTITY IN STOCK";Q%
320 LSET Q$=MKI$(Q%)
330 INPUT "REORDER LEVEL";R%
340 LSET R$=MKI$(R%)
350 INPUT "UNIT PRICE";P
360 LSET P$=MKS$(P)
370 PUT#1,PART%
380 RETURN
390 REM DISPLAY ENTRY
400 GOSUB 840
410 IF ASC(F$)=255 THEN PRINT "NULL ENTRY":RETURN
420 PRINT USING "PART NUMBER ###";PART%
430 PRINT D$
440 PRINT USING "QUANTITY ON HAND #####";CVI(Q$)
450 PRINT USING "REORDER LEVEL #####";CVI(R$)
460 PRINT USING "UNIT PRICE $$##.##";CVS(P$)
470 RETURN
480 REM ADD TO STOCK
490 GOSUB 840
500 IF ASC(F$)=255 THEN PRINT "NULL ENTRY":RETURN
510 PRINT D$:INPUT "QUANTITY TO ADD";A%
520 Q%=CVI(Q$)+A%
32
530 LSET Q$=MKI$(Q%)
540 PUT#1,PART%
550 RETURN
560 REM REMOVE FROM STOCK
570 GOSUB 840
580 IF ASC(F$)=255 THEN PRINT "NULL ENTRY":RETURN
590 PRINT D$
600 INPUT "QUANTITY TO SUBTRACT";S%
610 Q%=CVI(Q$)
620 IF (Q%-S%)<0 THEN PRINT "ONLY";Q%;"IN STOCK" :GOTO 600
630 Q%=Q%-S%
640 IF Q%= < CVI(R$) THEN PRINT "QUANTITY NOW";Q%;"REORDER
LEVEL";CVI(R$)
650 LSET Q$=MKI$(Q%)
660 PUT#1,PART%
670 RETURN
680 REM DISPLAY ITEMS BELOW REORDER LEVEL4
690 FOR I=1 TO 100
710 GET#1,I
720 IF CVI(Q$)<CVI(R$) THEN PRINT D$;"QUANTITY";CVI(Q$) TAB(50)
"REORDER LEVEL";CVI(R$)
730 NEXT I
740 RETURN
840 INPUT "PART NUMBER";PART%
850 IF(PART% < 1)OR(PART% > 100) THEN PRINT "BAD PART NUMBER":GOTO
840 ELSE GET#1,PART%:RETURN
890 END
900 REM INITIALIZE FILE
910 INPUT "ARE YOU SURE";B$:IF B$ < > "Y" THEN RETURN
920 LSET F$=CHR$(255)
930 FOR I=1 TO 100
33
940 PUT#1,I
950 NEXT I
960 RETURN
34
MODULE SEVEN
STRUCTURED PROGRAMMING, PSEUDOCODE AND ALGORITHMS
Structured programming is just a small part of the overall concept of structured design. The
root concept is to build a program from the top down. It also discards the concept of flow
charts. Here's the reason: Flow charts are unnecessarily detailed. By the time you break a
problem down to flowchart level, you can usually write the code directly. They're so
detailed, that few programmers go back and change them when the program changes, so
flow charts are usually out of date as soon as they're written.
Structured programming does use diagramming techniques, but for our purposes we'll be
able to use pseudocode for all our designs. We approach the problem by defining what we
want to do at a very high level. For example, to create a checkbook balancer, we might
outline the following steps:
| Enter initial balance |
| Add deposits |
| Subtract checks |
| Show final balance |
| Quit |
35
| subtract that amount from the balance |
| .... repeat as necessary |
| Show final balance |
| Quit |
Note that some items require more elaboration than others. In some cases, we could write
the Basic code directly, so there's no need for further refinement. Now, we're ready to write
the actual code. Using this structured, top down approach any problems become apparent
from the start.
This text based way of describing a program is termed pseudocode, because it's simpler than
English, but not rigorous enough to feed to the computer.
It forms a useful link between human and computer. Well written pseudocode is easily
converted to any language, and forms an outline of the program. It also suggests a
preliminary set of comments.
PSEUDOCODE
Before you write one piece of computer code, you have to know what the program is
supposed to do. Before you write one line of code in any language, it is a good idea to write
it in a simple way first to ensure you have included everything you need. The best way to set
this up is by using pseudocode.
Defining Pseudocode
Pseudocode is a simple way of writing programming code in English. Pseudocode is not
actual programming language. It uses short phrases to write code for programs before you
actually create it in a specific language. Once you know what the program is about and how
it will function, then you can use pseudocode to create statements to achieve the required
results for your program.
Understanding Pseudocode
Pseudocode makes creating programs easier. Programs can be complex and long;
preparation is the key. For years, flowcharts were used to map out programs before writing
one line of code in a language. However, they were difficult to modify and with the
advancement of programming languages, it was difficult to display all parts of a program
with a flowchart. It is challenging to find a mistake without understanding the complete flow
of a program. That is where pseudocode becomes more appealing.
36
To use pseudocode, all you do is write what you want your program to say in English.
Pseudocode allows you to translate your statements into any language because there are no
special commands and it is not standardized. Writing out programs before you code can
enable you to better organize and see where you may have left out needed parts in your
programs. All you have to do is write it out in your own words in short statements. Let's
look at some examples.
Examples of Pseudocode
Let's review an example of pseudocode to create a program to add 2 numbers together
and then display the result.
Start Program
Enter two numbers, A, B
Add the numbers together
Print Sum
End Program
Compare that pseudocode to an example of a flowchart to add two numbers
Now, let's look at a few more simple examples of pseudocode. Here is a pseudocode
to compute the area of a rectangle:
37
Get the length, l, and width, w
Compute the area = l*w
Display the area
Now, let's look at an example of pseudocode to compute the perimeter of a rectangle:
Enter length, l
Enter width, w
Compute Perimeter = 2*l + 2*w
Display Perimeter of a rectangle
Remember, writing basic pseudocode is not like writing an actual coding language. It cannot
be compiled or run like a regular program. Pseudocode can be written how you want. But
some companies use specific pseudocode syntax to keep everyone in the company on the
same page. Syntax is a set of rules on how to use and organize statements in a programming
language. By adhering to specific syntax, everyone in the company can read and understand
the flow of a program. This becomes cost effective and there is less time spent finding and
correcting errors.
Understanding Algorithms.
An algorithm is a procedure for solving a problem in terms of the actions that a program will
take and the order in which it will take those actions. An algorithm is merely the sequence of
steps taken to solve a problem. The steps are normally "sequence," "selection, " "iteration,"
and a case-type statement.
In C, "sequence statements" are imperatives.
The "selection" is the "if then else" statement.
The iteration is satisfied by a number of statements, such as the "while," " do," and
the "for."
The case-type statement is satisfied by the "switch" statement
SEQUENCE is a linear progression where one task is performed sequentially after
another. For example:
READ height of rectangle
READ width of rectangle
COMPUTE area as height times width
38
WHILE is a loop (repetition) with a simple conditional test at its beginning. The
beginning and ending of the loop are indicated by two keywords WHILE and
ENDWHILE. The loop is entered only if the condition is true. For example:
WHILE Population < Limit
Compute Population as Population + Births - Deaths
ENDWHILE
IF-THEN-ELSE is a decision (selection) in which a choice is made between two
alternative courses of action. A binary choice is indicated by these four keywords:
IF, THEN, ELSE, and ENDIF. For example:
IF HoursWorked > NormalMaximum THEN
Display overtime message
ELSE
Display regular time message
ENDIF
PROGRAM DOCUMENTATION
Program should not be written for one’s consumption only. On the contrary the beginner
should program as if it were meant for others to read and use. Therefore, documentation is a
very important activity in program development. The exercise should start from the problem
definition stage and continue throughout all other stages. Remember that readability is an
important feature of good programs.
SAMPLE PROGRAMS
Write a program to calculate the average of of 5 numbers
10 REM PROGRAM TO CALCULATE AVERAGE OF 5 NUMBERS
20 READ A, B,C,D,E
30 S1 = A+B+C+D+E
40 A1 = S1 /5
50 PRINT "AVERAGE" A1
60 PRINT "THE NUMBERS ARE", A,B,C,D,E
70 DATA 5,2,4,6,7
39
80 END
EXAMPLE 2
This program can be rewritten as
10 REM PROGRAM TO CALCULATE AVERAGE OF 5 NUMBERS
20 S=0, REM S IS FOR SUM
30 C=0, REM C IS A COUNTER
40 READ A
50 C= C+1; REM INCREASE C BY 1
60 S=S +A
70 IF C < 5 GOTO 40
80 A1 = S/C
90 PRINT "AVERAGE", A1
100 DATA 5,2,4,6,7
110 END
Example 3
This program can be rewritten using the For…Next statement.
10 REM PROGRAM TO CALCULATE AVERAGE OF 5 NUMBERS
20 S=0, REM S IS FOR SUM
30 FOR I =1 TO 5
40 INPUT A
50 S = S+A
60 NEXT I
70 A1 =S/5
80 PRINT “AVERAGE OF 5 NUMBERS = “; A1
90 END
Example 4
Write a program to compute the factorial of some numbers
10 REM PROGRAM TO COMPUTE FACTORIAL OF NUMBERS
20 FOR I= 1 TO 5
30 READ A
40 F =A
40
50 FOR J= N-1 TO 1 STEP -1
60 F = F* J
70 NEXT J
80 PRINT “FACTORIAL OF “; A, “=”; F
90 NEXT I
100 DATA 5,10,15,12,2
110 END
Example 5
Write a BASIC program to calculate the area of circles with 10 different radii
10 DEF FXN(R) = PI * R ^2
20 COUNT = 0
30 INPUT R
40 COUNT = COUNT +1
50 PI =3.142
60 PRINT “THE AREA OF A CIRCLE WITH RADIUS” ; R, “IS” , FNX (R)
70 PRINT
80 IF (COUNT <>10) THEN 30
90 END
Example 6
Write a BASIC program to calculate the sum and average of some numbers using arrays and
the FOR…Next statement.
10 REM PROG TO FIND THE SUM AND AVERAGE OF NUMBERS
20 DIM A(12)
30 LET S= 0
40 FOR I = 1 TO 12
50 READ A(I)
60 S = S+A(I)
70 NEXT I
80 A1 = S/12
90 PRINT TAB(10) “ THE SUM OF 12 NOS IS” S
100 PRINT TAB(10) “ THE AVERAGE OF 12 NOS IS “ A1
41
110 DATA 10,2,4,5,7,9,12,34,23,12,11,15
120 END
Example 7
Write a subroutine to compute the factorial of numbers
5 REM THIS PROG CALCULATES THE FACTORIAL OF NUMBERS
10 N=10; REM N IS THE TOTAL NUMBER
15 COUNT =0
20 READ NUM
25 COUNT = COUNT +1
30 GOSUB 50
35 PRINT FACT
40 DATA 10, 5, 3, 4 ,7, 8, 11, 12, 6, 9
45 END
50 FACT = NUM
55 FOR I = 1 TO NUM
60 FACT = FACT * J
65 NEXT I
70 RETURN
42