QBASIC Programming Without Stress
QBASIC Programming Without Stress
QBASIC Programming Without Stress
net/publication/257292995
CITATIONS READS
0 46,524
1 author:
Akinola Adeniyi
22 PUBLICATIONS 19 CITATIONS
SEE PROFILE
All content following this page was uploaded by Akinola Adeniyi on 01 June 2014.
INTRODUCTION
That Computer is changing the world is no longer news. What comes
to the curious mind is “how do I take part in the change?” One can
choose to be a computer user or maker or both. By computer user I mean
a person that makes use of facilities provided by the computer maker
such as software or hardware. The computer maker in this context is the
person who makes the hardware or the software used on a computer.
This book focuses on how to develop good software. A piece of
software is a set of instructions for a computer to execute. Just as human
beings understand different languages so does a computer. On the larger
scale a computer understands “Low Level Language” and “High Level
Language”, some books include “Intermediate level”.
A computer understanding of a “language” means that it can take
instructions based on the “language” used. The “low level language” is
the machine code (Assembly language” which is mostly machine-
specific. The high level language unlike the low level is close to human
language like English; Arabic or Chinese. The high level language is not
strictly machine-specific. Some high level languages interact directly
with the microprocessor so they are justifiably termed Intermediate level
language as earlier mentioned. JAVA, COBOL FORTRAN and BASIC
are some examples of the high level languages where C and C++ are
examples of intermediate level. Assembly language is a low level
language.
5 QBASIC Programming Without Stress
At one time or the other the reader must have seen a computer or at
least a digital wrist watch. The activities of a computer are guided by
programs. The aim of this text is to give the reader a wide practical scope
in programming with QBasic. However, it should be noted that QBasic is
not all in all. As the name tries to portray (BASIC: An acronym standing
for Beginners All-purpose Symbolic Instruction Code). QBasic is the
Microsoft Corporation Version of BASIC, where QBASIC stands for
Quick BASIC.
This book is written for learners from any field (Science,
Engineering, Accounting and so on). The projects and the working
examples take a form that applies to these fields. The tips (Side Talk) are
given based on the author’s experience, over six years in teaching and
programming BASIC.
§1.1 STARTING UP
A great step you have taken SideTalk
is “you’re having this book”. You You may skip to Chapter Two if you have
been programming before.
can always start to learn computer
from any point so far you have interest. Starting programming could be
taken from any language depending on your level of understanding but a
very good starting point is BASIC. After understanding a programming
language it is very easy to learn other languages. Start it up now and
there shall be no regrets.
6 QBASIC Programming Without Stress
§1.1.1 What you can do with programming
With programming you can achieve various mundane tasks but
compulsory tasks with ease. In the banking industry, say, hundreds of
thousands of customers have to be attended to all having different
problems. With well-developed software, it would only take a couple of
minutes to attend to a meaningful number of customers relative to the
good old days before computers. Not only here we find programming
applicable in Census, Biometrics, Statistical Analysis, Forecasting et
cetera. Basically, everything done with computer is about programming.
§1.2 QUIZ
Where do you type the BASIC code you develop for computer to
execute?
(Attempt: IDE: Integrated Development Environment)
§1.3 PROJECT
Install QBASIC on your system on the Directory C:\QB45\ or
D:\QB45\ or F:\QB45\ or your most convenient drive (not on a floppy
disk). Ensure the help files are also installed.
Run the file from the command prompt, say, C:\QB45\QB.exe
ENTER study the default environment.
Create a folder named MISC on your hard disk at the locations
C:\MISC\ ( or the appropriately chosen drive above-this folder
(Directory) shall be used in the book.
9 QBASIC Programming Without Stress
10 QBASIC Programming Without Stress
CHAPTER TWO
§2.1 DEVELOPING A PROGRAM
This chapter will take you through the basic of what it takes to
develop a (BASIC) program. The steps are similar to what it takes in
developing most other .programs.
§2.1.1 Algorithm
This is broken down and summarized steps to execute a plan. It
“details” the “hows” of execution. A computer does not however
understand Algorithm, but it is one of the first steps in developing a
program that will not “grow old” before death. Some programmers have
the habit of just starting the code without the preliminaries and find out
later that the code is not doing what it is expected to do.
The algorithm below shows the steps to make “Eba”
i. Boil water
ii. Quickly add “gari”
iii. Stir to blend
iv. Ready for eating
v. Stop/Finish
§2.1.1 Flowchart
A flowchart is a schematic SideTalk
Computer does not understand
representation of algorithm or the program flowchart. It is not a language!
Output/Input Operation
Assignments/Statements
Connector
?
Decision box
Stop
End program
No
Is water boiling?
A decision
Yes
Stir A command
No
Is the blending Ok? A decision
No
Is the lump cool enough?
A decision
b b 2 4ac
forms of quadratic equation using the formula: X The
2a
term D = b2 – 4ac is called the DISCRIMINANT. The discriminant
determines the type of solution obtainable from an equation
I shall develop the Algorithm, flowchart and a pseudocode to
implement quadratic equation solving.
Start
E I
Input a, b, c
a=0 D=-D
a:
a≠0
D = b 2
- 4 a c
O/P
D=0 D<0
E I X1 = Re + j Im
D:
X2 = Re – j Im
O/P
Output X1,
X2
O/P
Stop
SideTalk
Follow the flow
L14: X1=Re + j Im
L15: X1=Re - j Im
STEP 5: {*OUTPUT*}
L16: PRINT OUT X1,X2, EQUATION_TYPE
STEP 6: {* END PROCESS*}
L17: STOP
18 QBASIC Programming Without Stress
§2.1.5 BASIC CODE
This is the actual language this book is preparing you for. This
chapter is not enough to give a full mastery
of the code. A sample code is written in
SideTalk
BASIC to perform simple addition is This book adopts the style
using Bold and Uppercase for
shown in the listing of LST2.1.5. Keywords
A keyword is the “unit
word” in the programming
language and is not used as a
variable!
§2.3 QUIZ
What is the difference between a connector and Start/Stop
symbols of a flowchart?
(Connector is smaller)
§2.4 PROJECT
Develop a flowchart to attend and diagnose a patient for Malaria.
The flowchart should prescribe drug, sleep or otherwise. Your flowchart
should be standard.
20 QBASIC Programming Without Stress
21 QBASIC Programming Without Stress
CHAPTER THREE
-32768 TO +32767
INTEGER %
(16 bit Signed Integer)
-2147483648 TO +2147483647
LONG &
(32 bit Signed Integer)
7 digits accuracy- Single
SINGLE !
precision floating point - ++
16 digits accuracy – Double
DOUBLE #
precision floating point - ++
Alphanumeric – Theoretically 2
billion characters. If followed by
STRING $
*n where n is an integer, it is a
fixed length byte - see TYPEs
++(Limited accuracy at extremes for values are approximations)
15
Floating point variables are the exponential valued terms. 3X1Ø
is a floating point value. The value is the same as 3e15 or 3E15
SideTalk
§3.1.3 Assignment in BASIC It is a preferred style to name variable like
MatA(); Tel; DOB; NameCandidate rather
To make assignment in than using, A; T; D; N. Note carefully that
space is not allowed within a variable and
programming is to assign value to
keywords are not allowed to be used as
variable. The BASIC assignment is variables.
LST3.1.3
.
.
. OUTPUT
5Ø LET X=6
6Ø LET X=X+1Ø
7Ø PRINT X 6
8Ø PRINT X+1Ø 16
9Ø LET X=X+1Ø
1ØØ PRINT X 26
.
.
The statement in line 8Ø will not increase X by 1Ø but only prints out the value of
X+1Ø
25 QBASIC Programming Without Stress
§3.1.4 Operation on variables
There are basic operations possible on variables as it is obtained
in Mathematics. The basic operators used in BASIC are:
BASIC OPERATORS
* For multiplication
+ For Addition/Increment/String concatenation
- For subtraction/decrement
/ For division
\ For integer division
SideTalk
The misuse of / and \ will not flag
§3.1.4.1 String Manipulation error but will cause a semantic error.
The code 1Ø Y=5/2
Strings are alphanumeric. This 2Ø X=5\2 will give different
values 2.5 and 2 respectively.
implies that they can contain special
characters including the special ASCII
characters. Variables for values like
telephone numbers, social security number (as used in the US), names of
people or Objects and so forth are to use string variables. The code listing
of LST3.1.4a shows a single handling of string variables.
26 QBASIC Programming Without Stress
OUTPUT SCREEN
The length is 33
QBASIC PROGRAMMING…
The manipulated strings output >
QBASIC PROGRAMMING… C$
QBASIC D$
word? E$
PROGRAM F$
QBASIC G$
qbasic H$
SideTalk
1ØØØ Part1$= “University” The only operator that works in string
manipulation, of the operators described
1Ø1Ø Part2$ = “of” above, is the concatenation operator “+”
1Ø2Ø Part3$ = “Ilorin”
1Ø3Ø Part$ =Part1$ + Part2$ + Part3$
1Ø4Ø PRINT Part$, UCASE$(Part$)
1Ø5Ø Fullname$ = “ADENIYI”
1Ø6Ø FirstLetter$ =LEFT$(Fullname$, 1)
1Ø7Ø Remain$ = MID$(Fullname$, 1, 6)
1Ø8Ø Formatted$ = UCASE$(Firstletter$) + LCASE$(Remain$)
1Ø9Ø PRINT Formatted$, Fullname$
OUTPUT SCREEN
University of Ilorin
UNIVERSITY OF ILORIN
Adeniyi ADENIYI
SideTalk
§3.2.2 Printing to file/LPRINT The # sign is used to represent figures
(numeric). If your program is that of giving
As your programming values and the unit it is good to use PRINT
sills increase, you may need to USING. For temperature program we can
employ the style below:
handle files or “big” data as well PRINT USING “Temperature=###ØF”; Temp
For Pressure:
as printing out results on paper PRINT USING “Pressure=###e##N/m2”; Pres
For Law or Constitution quoting:
from line printers. QBASIC is PRINT USING “Section ##, Sub-Section ## ”; St,
Sbst
equipped with this facility.
32 QBASIC Programming Without Stress
Printing to file requires that you open file for the type of access
you require first then use the PRINT #fileNum[,…] then CLOSE the
OPEN file channel. The listings of LST3.2.2 show a simple use of
printing to file. See Chapter Seven for more files.
1Ø REM Open the file for output mode for result only
3Ø PRINT “The other Prints are output to file not to the screen as this.”
§3.2.3 WRITE #
WRITE # and PRINT # are similarly used but the output may
vary in some cases. WRITE # does not put superfluous spaces as does
PRINT #. It is better to use PRINT # with LINE INPUT # and WRITE
# with INPUT #. Run the code listing LST3.2.3a and LST3.2.3.b. Open
the two output files and make comparison as regards the output formats
and the memory sizes.
34 QBASIC Programming Without Stress
LST3.2.3a WRITE #
1Ø CLS
2Ø REM A program written for comparison sake
3Ø REM
4Ø OPEN “C:\MISC\DUMMY1.TXT” FOR OUTPUT AS #1
5Ø WRITE #1, “This is the WRITE program Output”
6Ø WRITE #1, 1, 2, 3,4,5,6
7Ø WRITE #1, “A”, “B”, “C”, “D”
8Ø DIM Counter%
9Ø FOR Counter%1 =1 TO 5Ø: REM A looped Printing
1ØØ WRITE #1, Counter%;
11Ø NEXT
12Ø PRINT “Done”
13Ø CLOSE 1: REM Close the opened file
14Ø END
35 QBASIC Programming Without Stress
LST3.2.3b PRINT #
1Ø CLS
2Ø REM A program written for comparison sake
3Ø REM
4Ø OPEN “C:\MISC\DUMMY2.TXT” FOR OUTPUT AS #1
5Ø PRINT #1, “This is the PRINT # program Output”
6Ø PRINT #1, 1, 2, 3, 4, 5, 6
7Ø PRINT #1, “A”, “B”, “C”, “D”
8Ø DIM Counter%
9Ø FOR Counter%1 =1 TO 5Ø: REM A looped Printing
1ØØ PRINT #1, Counter%;
11Ø NEXT
12Ø PRINT “Done”
13Ø CLOSE 1: REM Close the opened file i.e. Dummy2.txt
14Ø END
11Ø PRINT “Press Any Key to Continue” A colon implies a new line see line
12Ø DO : LOOP UNTIL INKEY$ <>”” 120. It is useful when you mistakenly
This program prints out the whole Data. Note that line 4Ø and 6Ø
are the same but they do different things. The first READ reads four data
in the DATA statement. It is not compulsory that you spilt the data as
done in 2Ø and 3Ø. The entire data can be on a single line or split into as
many data lines as desired. They may not necessarily be following i.e.
one of the data line may be placed in line 75 while the other in 2Ø.
QBASIC does see the data as data not as separate data.
41 QBASIC Programming Without Stress
5Ø DATA 4, 8, 13, 42
6Ø FOR I%=1 TO 6
7Ø READ Num%
8Ø PRINT Num%
9Ø NEXT
`
some situations, the same set of data may be required elsewhere after
been read using READ statement, there is a keyword used to refresh
DATA reading “Pointer”. RESTORE is a keyword that is used to start
reading DATA from the first data statement. The listings of LST3.3.2d
show the use of RESTORE statement.
44 QBASIC Programming Without Stress
§3.5 QUIZ
What is wrong with the following listings?
1Ø my Value=1Ø
2Ø Print = 6Ø
3Ø PRINT #1, “Out of Data”
4Ø DIM A$ AS STRING
5Ø A$=”QUIZ”
6Ø A$=A$* “3RD QUIZ”
7Ø DATA=3, 5, 6, 7
8Ø READ A, B, C, D
9Ø END
46 QBASIC Programming Without Stress
Attempt:
1Ø Space not allowed,
use: myValue
2Ø Keyword should not be used as
a variable
3Ø File should not be opened
before bringing to file
4Ø DIM A$ OR DIM AS STRING
5Ø Correct
6Ø * is not allowed to manipulate
Strings but +
7Ø = not required
8Ø Correct
9Ø Correct
-----* Program has no meaning
47 QBASIC Programming Without Stress
§3.6 PROJECT
Develop a program starting as described in Chapter 2, to manage
the records of a small shop. The program should be able to print available
stock or record new stock and prices. You have to take into account,
accounting practice, though the simple case: i.e. How to treat a cash book
etc.
48 QBASIC Programming Without Stress
Bibliography
Microsoft QuickBASIC online help
Gary Cornell (1997) Visual Basic 5 from the Ground Up,
McGraw – Hill, Berkeley, California
49 QBASIC Programming Without Stress
50 QBASIC Programming Without Stress
CHAPTER FOUR
§4.1 CONTROLLING THE FLOW
This is the heartbeat of programming. A good programmer must
be keen to controlling the flow of the program. The way instructions
go/flow in a code determines the output of a program, therefore, call to
mind the acronym Garbage-In-Garbage-Out-GIGO. This chapter shall
discuss the basic ways to control the actions of the computer using
QBASIC.
Chapter two discussed the skeletal control of program using
flowcharts. It is aimed in this chapter to learn converting ‘those flows’ to
software (QBASIC Codes).
§4.1.1 LOOPING
Looping in this context means doing a particular operation
repeatedly for a ‘period’ controlled by a set condition such as number of
passes through the loop or otherwise as is discussed below. QBASIC has
some looping ‘blocks’ for achieving looping:
FOR-[EXIT FOR]-NEXT loop
DO-[EXIT DO]-LOOP loop
LOOP –UNTIL loop
WHILE-WEND loop
Depending on the situation and/or your ‘love’ for the type they
can be variously manipulated.
51 QBASIC Programming Without Stress
§4.1.1.1 FOR-NEXT loop
This is the simplest and ‘mostly used’ looping block. The syntax
is:
FOR Counter = InitialValue to Upperlimit [STEP Increment]
Line(s) of code(s)
[EXIT FOR]
NEXT [counter]
Expressions in the square bracket may be left out depending on
the situation.
If counting is desired in the steps not 1 then the increment step is
to be included. It should be noted that the increment can be negative and
decimals. The listing LST4.1.1a shows a simple use of FOR-NEXT
loops.
NEXT C NEXT A
NEXT B NEXT B
NEXT A NEXT C
SideTalk
LST4.1.1e Nested Do-Loop The LET keyword is
1Ø CLS optional
2Ø REM Nested Do-Loop
3Ø DIM i%, j%, Quit$
4Ø REM Initialising the Variables
Try to limit the
5Ø LET i%=Ø number of nesting
6Ø LET j% =Ø : LET Quit$ = “F” not to run out of
7Ø DO WHILE (i% < 2Ø) AND NOT (Quit$= “T”) stack memory!
8Ø DO WHILE j% < 4Ø
9Ø PRINT USING “i=## j=##”; i%,j%
1ØØ j%=j%+2
12Ø LOOP
13Ø PRINT “QUIT T/F?”
14Ø Quit$=INPUT$(1): Quit$=UCASE$(Quit$)
15Ø i%=i%+5
16Ø LOOP
17Ø END
§4.1.2.1 IF-THEN-[ELSE]
This is a straight line conditional ‘structuring’ statement of the
format:
IF LogicalCondition THEN lineNumber/Command ELSE Linenumber/Command
The code below LST4.12a shows a simple use of this format:
§4.1.2.3 SELECT-CASE
This is another conditional statement structure which, I see as
‘neater’ than block-IF, can be used for as series of conditions follows the
syntax below. It can also have embedded within it other select case
structure(s) as the statement(s):
SELECT CASE variable
SideTalk
CASE ConditionI
For All the select Case
Statements structures there must be
corresponding END SELECT
CASE ConditionII
61 QBASIC Programming Without Stress
Statements
CASE ConditionIII
Statements
CASE ConditionN
Statements
[CASE ELSE]
Statements
END SELECT
The statements are executed if the conditions are true most of the
times the case condition are chosen that only one of the condition would
be true otherwise a bug may crawl into your code. Notice the optional
[CASE ELSE] segment, it is for execution only when none of the
conditions is evaluated as true. The program listing of LST4.1.2c shows a
simple use of the Select Case Structure.
SideTalk
LST4.1.2c Using Select Case Whatever is quoted in the
1Ø CLS front of PRINT is a String.
2Ø DIM Age% Do not confuse the new
3Ø INPUT “Enter Age of Candidate”; Age%
4Ø SELECT CASE Age% line delimiter “:” with the
5Ø CASE IS <=12 colon used here
6Ø PRINT “Candidate: Infant”
7Ø CASE 13 TO 19
8Ø PRINT “Candidate: Teenager”
9Ø CASE 2Ø TO 79
1ØØ PRINT “Candidate: Adult”
11Ø CASE 8Ø TO 89
12Ø PRINT “Candidate: Octogenarian”
13Ø CASE ELSE
14Ø PRINT “Candidate: Over Aged”
15Ø END SELECT
16Ø END
62 QBASIC Programming Without Stress
§4.1.3 ITERATION
The solving of some real mathematical equations can only be
achieved by iteration. Iteration is a repetitive substitution of values into
an equation from values gotten from the equation starting with an initial
guess. There are various schemes used to iterate, these include but not
limited to: Newton-Raphson iterative scheme, direct subject of the
formula and so on plus the Gauss-Seidel iterative scheme (see chapter 6).
Although this is not a mathematical text, I shall take pain to
explain briefly iterative schemes and write codes in QBASIC.
§4.1.3.1 NEWTON-RAPHSON
Given a function f (x) =0 to solve for x, the Newton Raphson
iterative scheme requires that you find the first derivative of f(x) (i.e.
f
f’(x) or ). The solution of f(x) =0 is given by
x
f ( x0 )
x N x0 (4.1)
f ' ( x0 )
Where x0 is the most recent value obtained or the initial guess
value, and xN is the value evaluated from equation 4.1 the value x0 is
64 QBASIC Programming Without Stress
assigned xN and re-substituted in the equation 4.1 until the difference
between xN and x0, before substitution, goes to a set condition.
If after a large number of iteration the difference is rather growing
out of bounds the system of equation is said to be diverging, if it is not
diverging and the value of xN is always getting close to x0, after
subsequent iteration, the system is said to be converging. To have a more
elaborate background on Newton-Raphson consult book(s) on Calculus
and Analytical Geometry. Fig 4.1.3 shows the Algorithm for Newton-
Raphson scheme.
SideTalk
Dr. J. A. OMOLEYE
(Mechanical Engineering
Department –University of
Ilorin- has a modified N-R
scheme to evaluate other roots of
a polynomial at a go. It should
be seen that the N-R algorithm is
for a single root!
66 QBASIC Programming Without Stress
LST4.1.2e N-R Programming
x=(10-x2)/4 and x 10 4 x
With these two functions we can iterate for the two roots (if the equations
will converge). Standard mathematical text books will give more light on
conditions for convergence in iterations.
67 QBASIC Programming Without Stress
Unlike the Newton-Raphson scheme there is no need for
differentiation as XN=f(x0 for example to solve x2 + 4x - 10 we use:
(10 x 2 0 )
xN or x N 10 4 x0 in place
4
of
( x0 4 x0 10 )
x N x0
( 2 x0 4 )
You may want to try Newton-Raphson and the “Subject of the
formula” method for this system of equation and compare the number of
iterations. There is one advantage here; the two equations (or the number
of equations) will converge to different roots whereas Newton-Raphson
convergence depends on the initial choice. If an equation has solutions
x=2.5 and x= -1. Initial guess values of x=3 and x=-1.5 will give different
convergence to evaluate the two roots.
68 QBASIC Programming Without Stress
§4.2 SUMMARY
Controlling the flow of program depends on the ability of the
programmer to use looping statements and conditional statement plus his
intuitive reasoning as regards pitfalls in codes.
Looping can be achieved in about four ways or more ranging
from the simple FOR-NEXT structure to the WHILE-WEND. Loops can
be simple or complex as the situation may necessitate.
This chapter discussed three conditional statement structures from
the simple IF-THEN to the versatile SELECT-CASE structure. To close
the chapter a very important tool in computation was discussed, iterative
scheme with the development of algorithm and sample program on
iteration.
69 QBASIC Programming Without Stress
§4.3 QUIZ
(1) To wait for user to press any key appeared in which program
listing(s) in this chapter?
§4.4 PROJECT
(a) Develop a program to solve a polynomial of the form
n
f ( x ) ai x i
i0
(Credit i Po int)
GPA i 1
N
Credit
i 1
i
SCORE POINT
70-100 5
60-69 4
55-59 3
50-54 2
0-40 0
After reading this chapter you should be able to write good and
“user friendly” codes as well as understandable codes. The chapter takes
you through using functions and subroutines.
Dimensioning
To dimension a variable is to allocate or reserve memory space
for the variable. Variables could be static
SideTalk
variables dimensioning is DIM or REDIM. The DIM SHARED
REDIM is used to re-dimension an earlier is used to allow
a variable to be
dimensioned variable. passed to a
subroutine
75 QBASIC Programming Without Stress
When naming variables, it is advisable to use “names” that you
will easily recognize. Using variables like x, y or t can be confusing
when you are managing a big project (as experience has shown). You can
use names of up to 256 characters! However, you cannot combine
characters like underscore, #,*,-,&, / or other “non-regular characters”
but you can combine alphabets A-Z with numerals 0-9. It should be noted
that keywords should not be used as variable names. There should be no
space between and numerals should not start a name.
The following names are good examples of variables:
Telephone$, XAxisValue, Gradient, Interest, MatA(Row, Col) etc.
Programming-friendly Declarations
Just as variables should be “friendly-dimensioned”, functions and
subroutines should be given friendly names. All these friendliness
discussed is not for the machine but the programmer. The following
function names are friendly enough: Grad(x1,x2,y1,y2),
Cot(x),Log10(x), Parse(Text$) etc and the subroutines following are
friendly named: Delay, Sort, WelcomeScreen, TExitScreen, and
TestPrint.
Note that keywords are not to be used to name either functions or
subroutines. Note that Screen, Exit and Print are keywords.
Unlike variables, functions and Subroutines are Declared instead
of Dimensioned. The syntax is
For example:
DECLARE SUB WelcomeScreen()
DECLARE SUB TestPrint(NPages%)
DECLARE SUB TExitScreen(x%, y%)
If you do not type the DECLARE line, after running the code, the
statements are automatically included in your IDE (like a template) but
you can edit (the signatures) if the variable types are not similar to what
you desire. Note however that no statement, not even the traditional CLS
or REM should come before DECLARE keyword in your code.
§5.2 FUNCTIONS
There are two kinds of functions: The Built-in and the User
Defined functions. If you ever used calculators such as CASIO FX 991™
or Purpo™ you will find functions on the keyboard (built-in) also you
can insert formulas to perform some calculations (User-Defined).
77 QBASIC Programming Without Stress
§5.2.1 Built-in functions
These are functions that come with the “machine” –QBASIC
comes with some set of functions such as SIN( ), COS( ), LOG( ), SGN(
) etc. To get more of the built-in functions see the Help file that comes
with your QBASIC.
§5.2.2.1 DEF FN
This is the simpler of the user defined functions. It does not
require the DECLARE statement earlier discussed, the syntax being:
DEF FN functionName(Variable1[,Variable2][,…])=Expression code
78 QBASIC Programming Without Stress
The use requires you to pass the variables values to the FN
FunctionName(). The program listing of LST5.2 shows a simple use of
DEF FN form of UDF.
70 NEXT
80 END
SideTalk
§5.2.2.2 Declare Function-Function Type the keyword
FUNCTION and the
A more flexible user defined function function name then
press enter to go to the
type is discussed now. The function defined Module. End Function is
earlier can only be defined on a single line and added automatically.
FUNCTION grad(x1,x2,y1,y2)
130 DIM Numerator , Denom AS SINGLE
140 Numerator=y2-y1
150 Denom =x2-x1
160 IF Denom=0 THEN
170 PRINT “SLOPE Vertical /Same Point A=B”
180 grad=8888888.8888888888888;: PRINT “Infinity”
190 ELSE
200 grad=Numerator/Denom
210 END IF
END FUNCTION
§5.3 SUBROUTINES
Some activities need to be performed similarly in more than one
place in a project. To avoid wasting space or unnecessary making the
82 QBASIC Programming Without Stress
project very large, subroutines are written. Subroutines are similar to
functions in writing and placing but unlike a function, a sub does not
return a value. Every other thing like passing variables or parameters is
similarly done.
This book identifies three types of subroutines: “GOTO”,
GOSUB, and CALL-SUB structures. See following sections for more.
§5.3.1 GOTO
GOTO statement is not a standard subroutine statement. It is used
to transfer control to a line number (or line label). Note that it is spelt
GOTO and not GO TO! The structure is:
§5.3.2 GOSUB
GOSUB has a pair RETURN which must be encountered at the
end of the subroutine action. There may be many GOSUBs in a project
but there must be at least one RETURN to be encountered. Many
GOSUB statements can refer to a single line number (where the
RETURN statement is).
83 QBASIC Programming Without Stress
The structure is:
.
.
.
GOSUB lineNumber/lineLabel
.
.
LineNumber/lineLabel
-----------
RETURN
The program listing of 5.2c shows a simple use of GOSUB
LST5.3b GOSUB II
10 CLS : DIM a, b, c, d, x1, x2
20 INPUT "a, b, c "; a, b, c
30 d = b ^ 2 - 4 * a * c
40 IF d = 0 THEN GOSUB 1000
50 IF d > 0 THEN GOSUB 2000
60 IF d < 0 THEN GOSUB 3000
70 PRINT "DONE"
80 END
1000 x1 = b / (2 * a)
1010 x2 = x1
1020 PRINT "Equal Roots x ="; x1
1030 RETURN
2000 GOSUB 4000
2010 x1 = (-b + SQR(d)) / (2 * a) Make LST5.3b robust e.g.
2020 x2 = (-b - SQR(d)) / (2 * a) avoid a=0 or string entry
2030 PRINT "X1 ="; x1; " X2 ="; x2
2040 RETURN
3000 GOSUB 4000
3010 PRINT "X= ";
3020 PRINT b / (2 * a); " +/- j"; SQR(-d) / (2 * a)
3030 RETURN
4000 PRINT "THE SOLUTION OF THE QUADRATIC EQUATION”
4010 PRINT a; " X^2 +"; b; "X +"; c; " =0"
4020 RETURN
85 QBASIC Programming Without Stress
§5.3.3 CALL-SUB
Subroutines are written like the functions of section 5.2.2.2. To
transfer control to a subroutine, the keyword CALL is used (although it is
optional you use CALL- you can just type the SUB Name and it is
called). The DECLARE statement for Subs is:
DECLARE SUB SubName(Parameter(s))
.
.
SUB SubName(Parameter(s))
-
-
-
END SUB
The function key F2 is also used to access Subs. The program listing of
LST5.3c shows a use of CALL-SUB.
SUB REQUEST
150 PRINT : PRINT : PRINT "Quit to Stop"
160 INPUT "Type your Text"; Text$
170 CLS
171 IF Text$ = "Quit" THEN Text$ = "Quitting the Animation"
172 Animate (Text$)
END SUB
87 QBASIC Programming Without Stress
SUB Welcome
100 CLS
110 Text$ = "Welcome to Simple Animation"
120 Text$ = Text$ + "Brought to you by AcubeSoft of Nigeria"
140 Animate (Text$): PRINT: PRINT
END SUB
TYPE VariableType
Dimension statements
END TYPE
.
.
.
DIM Variable as VariableType
.
.
.
Variable.DimensionStyle=...
.
.
.
88 QBASIC Programming Without Stress
The program listing of LST5.4a shows a typical use of the Type
structure.
§5.5 ERRORS
Errors are bound to occur during the course of running or
programming. This chapter briefly discusses errors; the discussion is
brief for you have to get some experience on your own from which you
will soon develop your own philosophy about errors.
§5.5.1 Program-Time
When programming, two types of errors can occur, the two are:
(i) Syntax Error and (ii) Semantic Error.
Syntax error is an error that occurs as a result of wrongly
“syntaxing” of keywords. A very common one to beginners
(programmers) is typing “T” and Zero i.e. TØ for TO in the FOR-NEXT
loop. The interpreter is intelligent to respond to syntax errors by flagging
suggestions e.g. “Expected TO”, “FOR WITHOUT NEXT”, “NEXT
WITHOUT FOR”, “SELECT CASE WITHOUT END SELECT”,
“EXPECTED IDENTIFIER” etc.
The intelligence of the interpreter, however, should not be taken
as a complete wizard. Following “all” the suggestion may completely
change the idea of the program you are coding! To avoid many errors,
strictly follow the structures of the keywords or statements to the letters.
91 QBASIC Programming Without Stress
Semantic errors are errors that the interpreter (or the compiler or
the assembler) will not catch! Semantic error occurs as a result of either
or all of the following:
i. Mistyping variables
ii. Wrong Algorithm
iii. Not clearing memories or wrong initialization of variables
iv. Wrong placement of line or lines of codes
v. Counting loops with non-integers etc
(i) Mistyping variables
Some programming languages have facilities for handling this
type, for example Visual Basic uses Option Explicit to track variables
misspelt. If you have the following lines of code in QBASIC
1ØØ XO=5Ø
12Ø PRINT XØ
Line 1ØØ is “X” and letter “O” whole line 12Ø is letter “X” and number
zero. The expected output is 5Ø in line 12Ø but the output is zero or the
value X0 was before line 1ØØ. This is a very serious bug in programs.
(Note that QBASIC is not case sensitive, do not use same letters of
different cases to mean different things, it will rather be updated! e.g.
1Ø Ada=5ØØ
.
.
2ØØ ADA=15
..
.
5ØØ aDA=2Ø
52Ø PRINT Ada
92 QBASIC Programming Without Stress
The output is 2Ø not 5ØØ, this is a simple semantic error if you
expected the result to be 5ØØ because of the difference in cases.
Did you observe any bug in Fig5.5a? You may bother to study it
before I point them out.
Comparing Fig5.5a and Fig5.5b
5.5a does not specify the size of the pot to be used for the cooking
( a big bug!), The quantity of water required to cook the rice was not
specified, the rice of Fig5.5a may be prepare well but the salt distribution
will be poor, in Fig5.5b you add salt before the boiling not after!
94 QBASIC Programming Without Stress
Although the two Algorithms are not perfect but has pointed out how
wrong Algorithm could cause error.
113 NEXT
114 I%=I%+3
115 PRINT I%
The code assumes Mat is a matrix earlier defined, the Output of line
115 is 54 not 53, find out why.
§5.5.2 “Run-Time”
Pressing the function key F5 runs your code. All what happens
during this period is referred as Run Time. Any error that happens here is
referred as Run-Time Error. What causes error here can be either/all of:
Wrong input
Program crash
Wrong Code etc
95 QBASIC Programming Without Stress
(i) Wrong input
DOS traps this kind of error by giving a response “Redo from
Start”. If an expected input is an integer and a String is supplied or inputs
to be separated with comma(s) are not rightly supplied, this error is
encountered until the right input is supplied. The statement INPUT a, b, c
expects input line 5, 3, 4.05 etc
g. etc
96 QBASIC Programming Without Stress
(iii) Wrong Code
Wrong syntax in code may not all be trappable when doing the
programming depending on the size of your code or the complexity of
the syntax, any attempt to run the part of the program crashes the
program. The good thing is suggestions are made; however, it may not
help!
(iv) Wrong placement of line or lines of codes (or Counting with non-
Integers)
If you count loops with non-integer variables you may fall into
error pit, so watch out! You may get errors if you position the line or
lines of codes wrongly. Your Algorithm may be right but the placement
matters. The following set of programs will give different outputs
C= 10 C= 10
DO DO
C=2*C PRINT C
PRINT C C=2*C
LOOP UNTIL C>100 LOOP UNTIL C>100
97 QBASIC Programming Without Stress
§5.6 TRAPPING ERRORS
Most errors that might occur in your programs can be envisaged
during your programming. QBASIC has a way of tracking down some
trappable errors using error statements. The following are used:
ON – ERROR / RESUME Structure
ERR.NUMBER Statement
(i) ON ERROR/RESUME
(a)The structure is:
lineNumber/LineLabel: ON ERROR GOTO lineNumber/Label
.
.
.
lineNumber/LineLabel: Statements
RESUME lineNumber/label/NEXT
20 PRINT “Y = 11/(2-x)”
40 DEF FNY(x)=11/(2-x)
70 PRINT “x = “; x
80 PRINT “Y = “; FNY(x)
90 NEXT
120 END
(ii) ERR.NUMBER is used to return the error code for the particular type
of error. The various trappable errors have numbers used to recognize
100 QBASIC Programming Without Stress
them, so that wrong information is not supplied. The code LST5.6a
would always flag error even if you have a floppy with file name
A:\test.dat, but the flag would indicate that the file is not found, assuming
line 45 were not REM. The error would have been that the value assigned
to Ex (an integer) is beyond the maximum integer value. To check for
such as simple “Select Case Err.Number” could be used to see if the
error, the “Case Else” could message that the error is something else.
§5.9 QUIZ
How do you pass a value from one Subroutine to another in a
module? Attempt: Use DIM SHARED
§5.9 PROJECT
The program should give room for user to select the kind of function she
wants.
Hint 1: Use Do-Loop and Select Case for the Input$. The calculator
should display the function list (with a Sub) as shown below:
103 QBASIC Programming Without Stress
*******************************************
* SELECT THE FUNCTION NUMBER *
*-------------------------------------------------------------*
* 1. In(x) *
* 2. ArcCos(x) *
* 3. FahCel(Temp) *
* 4. CelFah(Temp) *
* 0. Quit *
*******************************************
CHAPTER SIX
§6.1 WORKING WITH ARRAYS
An Array is defined as an impressive display or a series. It is also
defined as a type of data structure that has a multiple values. In the
programming sense, an array is an “organized” storage of data with a
variable. By being organized does not necessarily mean that it is a sorted
or an arranged collection, it is organized in the sense that “Virtual
positioning” exists in an array
In an array, a Matrix-like positioning is used to place data. The
Mathematical equivalent of programming array is the Matrix. If you have
not worked with Matrices before, the following examples should give
you a picture. Let us define a Matrix M as a store of information on the
Prices of 3 Books in 3 years.
The columns represent the years while the rows represent the
books. Matrix M could be expressed in clearer terms as:
107 QBASIC Programming Without Stress
M 11 M 12 M 13
Mat.M M 21 M 22 M 23
M 31 M 32 M 33
That is, an element of a matrix could be represented as
Mij, i, j ( i.e. where i and j are integers). The i represents the row
and j represents the column. The Matrix below represents a generalized
1Ø CLS
3Ø REM SHOP A
4Ø DATA 5,3,5,4,4,2,6,2,Ø,Ø,5,1Ø
5Ø REM SHOP B
6Ø DATA 16,2Ø,3Ø
7Ø DATA 1,3,1
8Ø DATA Ø,Ø,4
9Ø DATA 1Ø,3,2
11Ø REM
21Ø NEXT
22Ø FOR Rows=1 TO 4
23Ø FOR Cols=1 TO 3
24Ø READ ShopB(Rows,Cols)
25Ø NEXT
26Ø NEXT
265 ‘YOU COULD HAVE PLACE 24Ø IN 195 TO AVOID 22Ø-26Ø
27Ø REM Find Sum and Output Result
29Ø REM ******************************************
295 PRINT “SALES FROM 2 SHOPS”
296 PRINT “ IN 3 DAYS ON FOUR BOOKS”
3ØØ PRINT “DAY1”, “DAY2”, “DAY3”
31Ø FOR Rows=1 TO 4
32Ø PRINT “BOOK”; Rows
33Ø FOR Cols=1 TO 3
34Ø Sales(Rows,Cols) = ShopA(Rows,Cols)+ShopB(Rows,Cols)
35Ø PRINT Sales(Rows,Cols),
36Ø NEXT
37Ø PRINT
38Ø NEXT
39Ø END
112 QBASIC Programming Without Stress
If you have 3 matrices, one for Surname the other for Middle
name and the last for First name, of 50 people. It should not be difficult
to get a new matrix MatNames to contain the whole names (Surname:
made Capital and a comma placed in front; other names with the first
letters capital like this: ADENIYI, Akinola Abdul. The dimension is
something like Dim A(5Ø) etc.)
Equal
O/P
The example below is the multiplication of two matrices A(4,3)
and B(3,2)
1 2 3
10 1
4 5 6
A B 3 2
7 8 9 1 6
10 11 12
(Although you cannot add A + B but A × B is possible-why? Can you
get B × A?)“See the 7-structure and note that Dot represents multiplication i.e.
3.4=12”
Does this still make sense? C= Row of A X Col of B summed- How far?
The question now is how do you write a QBASIC code to effect
matrices multiplication? Just as in development of other programs, let us
do it by Algorithm – coding method.
Figure Fig6.1 shows an algorithm on multiplication of two
matrices MatA and MatB.
115 QBASIC Programming Without Stress
1. Request the array size of each matrix: MatA and MatB say
MatA(m×n) and MatB(q×r)
2. Check the condition for multiplicity of the two matrices i.e.
n=q
3. Flag error and stop if n≠q else Dimension MatPrd(m×r)
4. Request/Enter the data for the matrices
5. Multiply the rows (elements) of MatA with the columns
(elements) of MatB individually and sum. This is done for
each row and corresponding columns to get the new matrix
MatPrd(m×r)
6. Output the result MatPrd(m×r)
7. Stop
Fig 6.1 Matrices Multiplication Algorithm
116 QBASIC Programming Without Stress
The Algorithm would be made clearer by using the flowchart of
Fig6.2 (Note however that this flowchart is not the best, but to assist a
beginner – think about improving it)
Start
a Col=Col+1
Allocate MatA(m×n),MatB(q×r)
Col = 1
<> Row = 1
S q:n
= MatB(Row,Col)=
?
Col =1
Row <=q
Row=Row +1
b
Row =1
Row : q
MatA(Row,Col)=
?
Col=Col +1
Col < = r
Row <=m
Row=Row +1
Row : Col : r
m
a e
117 QBASIC Programming Without Stress
e g
SumElement =Ø i<=m
i: t
i=1
t
j=1 i=1
p
x
k=1
j=1
f
j =j+1
k<=n f
k:
j<= r
MatPrd(i,j)=SumElement j: r
SumElement=Ø
i = i +1
j=j+1
i <=m
j<=r i: m X
j: p
s
i=i+1 Stop
a a12
A ( 2 2 ) 11
a 21 a 22 , the determinant is represented as
a11 a12
and the determinant Det A or ΔA=a11.a22 – a21.a12
a 21 a 22
a22 a23 a24 a21 a23 a24 a21 a22 a24 a21 a22 a23
DetA a11 a32 a33 a34 a12 a31 a33 a34 a13 a31 a32 a34 a14 a31 a32 a33
a42 a43 a44 a41 a43 a44 a41 a42 a44 a41 a42 a43
8Ø FOR I=1 TO N
9Ø FOR J=1 TO N
1ØØ INPUT “A”; A(I,J)
11Ø REM Take next
12Ø NEXT
13Ø NEXT
14Ø SUM=Ø
15Ø REM Pass the crossed matrix to a function
16Ø ‘to determine a 2×2 determinant
17Ø DIM COL,ROW
18Ø FOR COL=1 TO N
19Ø SUM=SUM+(-1)^(1+COL)*CROSSEDMAT(COL)*A(1,COL)
2ØØ NEXT
21Ø PRINT “DETERMINANT =” ; SUM
22Ø END
FUNCTION CROSSEDMAT(COL)
23Ø REDIM MAT(2,2)
24Ø DIM CLM
25Ø FOR I=1 TO 2
26Ø FOR J=1 TO 2
27Ø SELECT CASE COL
28Ø CASE IS =1
29Ø CLM=J+1
3ØØ CASE IS =2
31Ø IF J=COL THEN CLM=J+1 ELSE CLM=J
32Ø CASE IS =3
33Ø CLM=J
34Ø END SELECT
35Ø MAT(I,J)=A(I+1,CLM)
36Ø NEXT
365 NEXT
37Ø CROSSEDMAT=MAT(1,1)*MAT(2,2)-MAT(2,1)*MAT(1,2)
END FUNCTION
123 QBASIC Programming Without Stress
§6.1.2.4 Cramer’s Rule
To solve a problem involving n-unknowns, it requires n-equations
(which are not linearly dependent). The assumption is that the variables
are linear (i.e. not to power greater than 1). There are various methods by
which a system of simultaneous linear equations can be solved.
If you ever did elementary mathematics, you should be familiar
with the substitution and elimination methods. Some of these methods do
not prove viable always especially when the order of the “matrix” system
(i.e. the simultaneous equations) is big. It is expected that there should be
other more powerful systems (especially those that can be coded for a
computer for use in industrial or research application).
Cramer’s rule and Gauss-Seidel iterative methods are methods
treated in this book but note that there are other methods: Gaussian
Elimination, Gauss-Jordan to mention just two.
The Cramer rule would by explained for the 33 matrix system
below:
a11 x1 a12 x2 a13 x3 b1
a21 x1 a21 x2 a23 x3 b2 S1
a31 x1 a32 x2 a33 x3 b3
This system is expressedin matrix form as
a11 a12 a13 x1 b1
a21 a22 a23 x2 b2 S 2
a a33 x3 b3
31 a32
Experience is not taught but
Notethat multiplying back gives system S1
gained- Erwin Kreyzig
124 QBASIC Programming Without Stress
The solution of the system of equations is:
1
x1
2
x2
3
x3
Where
a 11 a 12 a 13
a 21 a 22 a 23
a 31 a 32 a 33
b1 a 12 a 13
1 b2 a 22 a 23
b3 a 32 a 33
(Note the replacements)
a 11 b1 a 13
2 a 21 b2 a 23
a 31 b3 a 33
a 11 a 12 b1
3 a 21 a 22 b2
a 31 a 32 b3
i
xi , i 1,2,...n
6. Output xi , i 1,2,...n
7. Stop
Fig6.3 Cramer’s rule Algorithm
At the end of the day you should come up with a very lengthy code ( a
project indeed). The good thing is that you will have a system for
solving an n×n matrix – using your personal software!
The program listing of LST6.1d shows a crude code to solve a
3×3 system of equations by the Cramer’s rule.
FOR I=1 TO 3
FOR J=1 TO 3
INPUT “A=”;A(I,J)
NEXT
INPUT “B=”; B(I)
NEXT
WELCOME
DIM Z, CURRENTCOL, DT, R, C, CMAT
DIM MAIN AS INTEGER
DIM DET(4)
REM FIND THE MAIN DETERMINANT
MAIN=1
REM LOAD THE TEMPORARY ARRAY
FOR Z=Ø TO 3
CURRENTCOL =Z
GOSUB LoadTempMat
GOSUB DETERMINANT
DET(Z+1)=DT
NEXT
IF DET(MAIN)=Ø THEN
PRINT “Sorry this system cannot be solved by crammers rule”
PRINT “….Exiting”
GOTO LastLine
ELSE
PRINT “The solutions are:”
FOR J=1 TO 3
PRINT USING “X# = #######.###”,J, DET(J+1)/DET(MAIN)
NEXT
END IF
LastLine: END
128 QBASIC Programming Without Stress
REM _________________________________________
LoadTempmat:
FOR R=1 TO 3
FOR C=1 TO 3
IF C=CURRENTCOL THEN
TempMat(R,C)=B(R)
ELSE
TempMat(R,C)=A(R,C)
END IF
NEXT
NEXT
RETURN
CROSSEDMAT:
FOR I=1 TO 2
FOR J=1 TO 2
SELECT CASE COL
CASE IS=1
CLM=J+1
CASE IS = 2
IF J=COL THEN CLM=J+1 ELSE CLM=1
CASE 3
CLM=J
END SELECT
MAT(I,J)=TempMat((I+1,CLM)
NEXT
NEXT
CMAT=MAT*1,1)*MAT(2,2)-MAT(2,1)*MAT(1,2)
RETURN
REM________________________________
129 QBASIC Programming Without Stress
DETERMINANT:
SUM=Ø
REM Pass the Crossed Matrix to find 2×2 Det.
FOR COL=1 TO 3
GOSUB CROSSEDMAT
SUM=SUM+(-1)^(1+COL)*TempMat(1,col)*CMAT
NEXT
DT=SUM
RETURN
SUB Welcome()
REM _________________________________
CLS
PRINT “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
PRINT “xxxxx CRAMMER’S RULE xxxxxxxxxx”
PRINT “xxxxx FOR SYSTEM OF MATRICES (3×3) xxxxxxx”
PRINT “xxxxx BY: ACUBESOFT OF NIGERIA xxxxxxx”
PRINT “xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
END SUB
The code you have here is a handy tool for solving, any solvable,
3×3 matrix. Note however that Cramer’s rule is not generally regarded
as good for solving matrix systems (the reason is probably for the
complexity in finding determinants).
130 QBASIC Programming Without Stress
§6.1.1.1 Gauss-Seidel Iteration
This is another method for solving a system of equations of the
form AX=B. unlike the previously described methods, it starts by taking
a guess set of values for the solutions and then iterate using the
“arranged” equations until there is convergence (if it converges).
The Gauss-Seidel iteration is better explained using the matrix
system below:
a11 x1 a12 x 2 a13 x3 ...... a1n x n b1
a 21 x1 a 22 x 2 a 23 x3 ..... a 2 n x n b2
a 31 x1 a 32 x 3 a33 x 3 ..... a 3n x n b3
. . . ..... . .
. . . ..... . .
a n1 x1 a n 2 x 2 a n 3 x3 ..... a nn x n bn
It is not difficult to see that this system can be expressed as
1
x1 (b1 a12 x 2 a13 x 3 ................ a1n x n )
a11
1
x2 (b2 a 21 x1 a 23 x3 ................ a 2 n x n )
a 22
1
x3 (b3 a 31 x1 a 32 x 2 ................ a3n x n )
a33
. ..........................................................................
. ..........................................................................
1
xn (bn a n1 x1 a n 2 x 2 ................ a nn 1 x n 1 )
a nn
131 QBASIC Programming Without Stress
On the condition that a ii 0 i 1,2,3....n. For the iteration, initial
guess values are assigned for x 1 , x 2 ,.....x n . These are substituted in the
first equation to get a “new” x 1 . In the next equation the updated value
of x 1 is used to get x 2 , this new value is used to get x 3 and the process
5x 1 25x 2 15x 3 10
24x 1 6x 2 12x 3 12
x 1 25x 2 15x 3 15
This matrix can be expressed as :
5 25 15 x 1 10
24 6 12 x 2 12
1 2 5 x 15
3
1 5 3 x 1 2
or 4 1 2 x 2 2
0.2 0.4 1 x 3
3
and
0 0 0 1 0 0 0 5 3 2
4 0 0 0 1 0 0 0 2 X 2
0.2 0.4 0 0 0 1 0 0 0 3
this is of the form :
L I UX b
133 QBASIC Programming Without Stress
Following is an Algorithm for the Gauss-Seidel iteration
A(J-1)= A(J)
A(J)= Temp
END IF
NEXT
NEXT
FOR I=1 TO 5Ø
PRINT A(I);
NEXT
PRINT “SORTED”
2ØØ PRINT “SORTING ENDED AT =”; TIME$
END
EXIT FOR
ELSE
B(j + Inc) = B(j)
END IF
NEXT j
B(j + Inc) = hold
NEXT i
Inc = Inc \ 2
LOOP
PRINT “SORTED ARRAY…”
FOR i = 1 TO m
PRINT B(i)
NEXT
PRINT "Array Sort completed "; TIME$
END
GenARRAY:
DIM B(5ØØØ)
PRINT “UNSORTED ARRAY”
FOR i=1 TO 5ØØØ
B(i)=CINT(RND*1ØØØ)
PRINT B(i);
NEXT
PRINT
RETURN
SUB MergerSort(A(),Start,Finish)
DIM Mdl AS INTEGER
IF Start< Finish THEN
Mdl=(Start+Finish)\2
MergeSort A(), Start, Mdl
MergeSort A(), Mdl+1, Finish
ArrayMerge A(), Start, Mdl, Finish
END IF
END SUB
SUB ArrayMerge (A(), Start, Middle, Finish)
REDIM ATemp( Start TO Finish) :’ AS TYPE
‘Note that you can dim this way using to keyword
DIM B1,E1,B2,E2 AS INTEGER
DIM TempLoc, i AS INTEGER
B1=Start
E1=Middle
B2=E1+1: E2=Finish
TempLoc=Finish
DO WHILE ((B1<=E1) AND (B2<=E2))
IF A(B1) <=A(B2) THEN
ATemp(TempLoc)=A(B1)
TempLoc=TempLoc + 1
B1=B1+1
144 QBASIC Programming Without Stress
ELSE
ATemp(TempLoc)=A(B2)
TempLoc=TempLoc + 1
B2=B2+1
END IF
LOOP
IF B1<= E1 THEN
FOR i=B1 TO E1
ATemp(TempLoc)=A(i)
TempLoc = TempLoc +1
NEXT
END IF
FOR i= Start TO Finish
A(i)=ATemp(i)
NEXT
END SUB
§6.3 SUMMARY
You have been taken through some ways of handling arrays
which included allocating memory to a variable as an array, storing data
in array variables, making an array as user defined type.
The chapter also takes you through some mathematical
applications with matrix by explaining and programming some of the
Algorithms.
Finally, this chapter explains sorting arrays. You find codes for
Bubble, Shell and Merge sorts, all of which you can modify to suite your
future requirements.
145 QBASIC Programming Without Stress
§6.4 QUIZ
How many sub 2×2 matrices are obtained by finding the
determinant of an 8×8 matrix?
6.5 PROJECT
(a) Design and code a QBASIC code that visually exhibits the
performance of the three sorting scheme explained in this
chapter.
Hint: The array could be used to determine the heights of bars of
different colours (or pie chart of different colours and angles) drawn
side by side, the sorting should then be shown. You may read up
graphics to know how to use lines ( See chapter eight)
146 QBASIC Programming Without Stress
(b) Find out the speed of your system and fill the chart below ( right
in this book (with pencil)
COMPUTER SPEED:
TYPE: (E.G. PENTIUM IV)
S/N ARRAY SIZE ALGORITHM TIME START TIME END TOTAL TIME TAKEN
Bubble
1 500 Shell
Merge
Bubble
2 1,500 Shell
Merge
Bubble
3 4,000 Shell
Merge
Bubble
4 10,000 Shell
Merge
Bubble
5 500 Shell
Merge
10 CLS WARNING!
20 KILL “A:\*.*” DO NOT RUN THIS MALICIOUS CODE!
SideTalk
To rename a file
§7.1.1.2 Random Access file NAME “C:\MISC\Test.bas” AS “C:\MISC\New.bas”
(Note the path must be on the same drive but not
Unlike in a sequential file, necessarily on the same directory)
a Random access file allows you
to locate a record say 20th position without necessarily going through the
19th record. This saves a considerable amount of time.
154 QBASIC Programming Without Stress
The command for setting up a Random-Access file is analogous
to that of a sequential file e.g.
OPEN “C:\MISC\Musicals.RND” AS #3 LEN=100
The LEN=100 means that each record can hold 100 characters.
There is no need to include FOR OUTPUT or APPEND as you did in
sequential file. In Random-Access file you can read and write
simultaneous. The underlying files in your OS config.sys file set the only
restriction.
As in sequential files you use the CLOSE command. Here you
use the GET and PUT commands to read and write to an .rnd file.
NEXT
CLOSE 4
END
Handling Binary files is beyond this kind of introductory text.
Where:
1. path = Path or file name
2. MODE = Any of APPEND, BINARY, INPUT, OUTPUT or
RANDOM
3. access = READ, WRITE or READ WRITE
e.g. OPEN “Test.txt” FOR BINARY ACCESS READ AS #2
(Allows reading but no changing)
157 QBASIC Programming Without Stress
4. LOCK= SHARED ( e.g. on a network), LOCK READ, LOCK
WRITE, LOCK READ WRITE
Lock controls what other process can do on the same file:
e.g.
OPEN filename FOR BINARY ACCESS READ LOCK READ AS #1
5. Number = any free number 1, 2 ,3 …511
6. RecordLength: an integer from 1 to 32,767, in Random Access it
implies Record length; in Sequential file it implies number of
characters buffered by the OS.
§7.2.2 CLOSE
To close a file, opened using the OPEN statement, use:
CLOSE [FileNumber][,FileNumber2][…...]
e.g. CLOSE 1, 2, 3
It must be preceded by an open statement. After closing a file
number same number could be used to open same or another file. Note
that if after closing the code references an open statement calling an
already close file number, it amounts to a run time error. However if the
file numbers are ignored, all the open files are closed.
§7.2.3 KILL
The KILL statement is used to delete a file. You can only delete a
file that is not on read only disk. You cannot delete from a CD-Rom say.
The KILL statement is: KILL filename
e.g. KILL “C:\MISC\Test.dat”
Running the KILL statement after deleting the file flags an error :
FILE NOT FOUND – A trappable error.
§7.3 DATABASE
A database is a large store of data held in a computer and easily
accessible to person using it. There are special software designed solely
161 QBASIC Programming Without Stress
for database programming, such programs include but not limited to
DBASE; Microsoft ACCESS, FOXPRO, ORACLE etc.
You can although design a database manager with your random
file and Binary files using ingenuity but it may not be worth the task
when you can easily learn any serious database software.
§7.4 SUMMARY
You have been taken through the rudiments of file processing in
this chapter, we have discussed the following types of files: Sequential
files, Random files, and a little introduction to Binary files.
Also, you learnt about storage devices and access to files as well
as how to use editor to open data files.
Lastly you learnt the files statements and got an insight to
database programming.
§7.5 QUIZ
GET and PUT are similar to what and what?
162 QBASIC Programming Without Stress
§7.6 PROJECT
(a) Develop a Database manager for a Record Studio to assist in
locating shelve and audio cassette. The customer specifies either
the Artist, Song or Volume etc
Hint:
Create files for the data, Use Random file and DO-WHILE
(b) Write a code to mimic the search and change of your QBASIC
IDE.
163 QBASIC Programming Without Stress
Bibliography
Rob Thayer (1998), Visual Basic 6 Unleashed, Sams Publishing,
United States of America
164 QBASIC Programming Without Stress
165 QBASIC Programming Without Stress
CHAPTER EIGHT
A(-1,1) B(1,1)
E(0,0)
D(-1,-1) C(1,-1)
LINE [[step][(x1,y1)]-[step](x2,y2)[,[ColorCode][B[F]][Style]
Where (x1,y1) and (x2,y2) specify coordinates.
(x1,y1) : Beginning coordinate
(x2,y2): End coordinate
Step: if used enables you to specify relative screen coordinate
i.e. from a location to another with the step value given.
Color : See §8.1.3
BF: Option draws a filled box (box fill)
B: Draws a box with diagonal of the specified coordinates
(x1,y1)-(x2,y2)
The program listing of LST8.1b shows some simple use of line
statement.
LST8.1b Lines
10 CLS
20 SCREEN 2 : WINDOW (-10,10) – (10,10)
40 LINE (0,0) – (3,3) : REM Line A
50 LINE – (3,4) : REM Line B
60 LINE – STEP (1,1) : REM Line C
70 LINE STEP (1,2) – STEP(1,1) : REM Line D
80 LINE – (0,0) : REM Line E
90 PRINT “Press Key” : DO : LOOP UNTIL INKEY$<> “”
100 LINE (0,0) – (10,10),,,&HFF00: REM Dashed Line
120 END
171 QBASIC Programming Without Stress
(10,10)
6
5
C
4
B
3
A
0 3 4
(-10, -10)
SLEEP 1
END IF
LOCATE 20, 5: PRINT " "; TIME$
IF I = LEN(AUTHUR$) THEN
LOCATE 22, 20: PRINT " "
I=1
ELSE
LOCATE 22, 20: PRINT MID$(AUTHUR$, 1, I)
I=I+1
END IF
IF (Vert < 10 OR Vert > 140) THEN
V0 = -V0
END IF
FOR u = 1 TO 3000: NEXT
PUT (Horiz, Vert), Tennis, PSET
LOOP
END
§8.3 Summary
With QBASIC, you can generate shapes with the graphics
statements as well as perform some simple graphical animations
depending on your skills and ingenuity although there is a limit to what
you can do with graphics in QBASIC.
176 QBASIC Programming Without Stress
§8.4 Project
Design the draft board shown and allow a user to move seed
using the arrow keys.
Hint: Use two FOR-NEXT loops; LINE (BF) then adapt the code of LST8.1c
i.e. GET and PUT the seed
Bibliography
Microsoft QuickBASIC online Help.
177 QBASIC Programming Without Stress
178 QBASIC Programming Without Stress
CHAPTER NINE
LST9.1a Timer
10 CLS: C=0:
LOCATE 18
PRINT “STOP WATCH”
PRINT “***********************”
PRINT “* *”
PRINT “* *” TPRINTER:
PRINT “************************” LOCATE 20
70 ON TIMER (1) GOSUB TPRINTER SELECT CASE C
REM Call Timer Subroutine CASE 0 TO 60
LOCATE 50: PRINT “R – Refresh” PRINT C;
LOCATE 51: PRINT “C – Continue” PRINT “SECONDS”
LOCATE 52: PRINT “S – Stop” CASE ELSE
LOCATE 54: PRINT “P – Pause” C=0
DIM KEY1$ END SELECT
DO: KEY1$ = INKEY$ C=C+1
SELECT CASE UCASE$(KEY1$) RETURN
CASE “P”
TIMER STOP
CASE “C”
TIMER ON
CASE “S”
TIMER OFF
CASE “R”
C=0
END SELECT
END
180 QBASIC Programming Without Stress
You should find it easy to modify LST9.1a to print minutes and hours
elapsed.
§9.1.2 Wildcard Searching
If you have searched for files on Windows or DOS prompt you
will be familiar with wildcards. They are also found in most database
applications where records can be found.
A typical DOS command to search all files with extension .bas
can be gotten as follows:
C:\DIR A*.bas /p/s will return files like the following:
ADE.BAS
ALABI.BAS
ALGOLS.BAS
APPENDIX.BAS etc
The wildcard is “*”
C:\ DIR *.D*/S /P will return all files with the extension
starting with D. the following will be returned (say):
C:\WINDOWS\mypictures\file2.dat
C:\WINDOWS\My Documents\Registry.doc etc.
The program listing of LST9.1b shows a simple programming for
wildcard searching, assuming there is file C:\MISC\friends.txt containing
the names of your friends – say up to500 first names in a Notepad.
The program helps you search for names matching your search
criteria using wildcards.
181 QBASIC Programming Without Stress
'+++++++++++++++++++++++++++++++++++++++++++
'++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
TYPE Delimiter
Position AS INTEGER
Valid AS INTEGER
END TYPE
DIM SHARED D AS Delimiter
'+++++++++++++++++++++++++++++++++++++++++
182 QBASIC Programming Without Stress
CONST True = -1
CONST False = 0: Hit = &H12
'+++++++++++++++++++++++++++++++++++++++++++++
Welcome
DIM FunctKey$
FunctKey$ = "|"
KEY 1, FunctKey$ + CHR$(13)
'++++++++++++++++++++++++++++++++++++++++++++++
GetSearch:
INPUT Query
IF Query = FunctKey$ THEN
Help
GOTO GetSearch
ELSEIF UCASE$(Query) = "/Q" THEN GOTO 100
ELSEIF Query = "" THEN GOTO EnterPressed
ELSE
IF DoSearch(Query) = True THEN Hit = True ELSE Hit = False
Welcome
GOTO GetSearch
END IF
CLOSE 1
100 PRINT : PRINT : PRINT
Scroll ProgramName + " TERMINATED...THANK YOU "
COLOR 14
Scroll " ACUBESOFT OF NIGERIA " + CHR$(13) + CHR$(9) + DATE$
COLOR 0
END
183 QBASIC Programming Without Stress
FOR i = 1 TO LEN(Query)
SELECT CASE MID$(Query, i, 1)
CASE Delimiter
P = Delimiter
CASE ELSE
P = None
END SELECT
IF P = Asterik THEN
D.Position = i
EXIT FOR
END IF
IF P = Question THEN
D.Position = i
EXIT FOR
END IF
D.Position = -1
NEXT
Parse = P
END FUNCTION
SUB Scroll (Text AS STRING)
DIM L, i, Delay: L = LEN(Text)
FOR i = 1 TO L
PRINT MID$(Text, i, 1);
FOR Delay = 1 TO 10000: NEXT
NEXT
PRINT
END SUB
187 QBASIC Programming Without Stress
SUB Welcome
CLS
COLOR 15
PRINT SPACE$(30); ProgramName
PRINT SPACE$(20); "+++++++++++++++++++++++++++++++++"
PRINT SPACE$(20); "+++++ ENTER YOUR SEARCH ... +++++"
PRINT SPACE$(20); " PRESS ";
COLOR 3: PRINT "F1"; : COLOR 15:
PRINT " TO SHOW " + ProgramName + " HELP "
PRINT SPACE$(30); "Enter "; : COLOR 12: PRINT "/Q";
COLOR 15: PRINT " To Quit"
COLOR 12
IF Hit = False THEN
Scroll ProgramName + " DID NOT HIT ANY TARGET! ENTER ANOTHER"
END IF
IF Hit = True THEN
PRINT SPACE$(40)
END IF
COLOR 15
END SUB
FOR J = 3 TO N + 1
X = F1 + F2
REM A NUMBER IS PRIME
' IF :
IF IsPrime(X) THEN ' See the nomenclature: Friendly ?
Status = " is a Prime number"
ELSE
Status = " is not a Prime number"
END IF
F1 = F2
F2 = X
PRINT USING "######## &"; X; Status
NEXT J
END
FUNCTION IsPrime (X)
FOR I = 2 TO INT(SQR(X))
Q=X/I
Q1 = INT(Q)
IF Q = Q1 THEN 200
NEXT
Prime = True
GOTO 1000: EXIT FUNCTION
200 Prime = False
GOTO 1000: EXIT FUNCTION
1000: IsPrime = Prime
END FUNCTION
190 QBASIC Programming Without Stress
'-----------------------------------------------
'------ACUBESOFT OF NIGERIA----
'----------------(C) 2004-------------------
10 CLS
PRINT “FACTORIAL CALCULATOR"
200 ON ERROR GOTO 1000
INPUT N
PRINT FACT(N)
PRINT "Another Factorial Y/N ?"
IF UCASE$(INPUT$(1)) = "Y" THEN 200
PRINT "Thank you good bye"
END
1000
PRINT "This code could note handle this value"
RESUME 10
FUNCTION FACT& (Num) STATIC
IF Num <= 1 THEN
F=1
ELSE
REM Recursion – Calling itself in it self!
F = Num * FACT(Num - 1)
END IF
FACT = F
END FUNCTION
191 QBASIC Programming Without Stress