VP Notes
VP Notes
3. PROGRAM STRUCTURE
Format of Visual Program
Data types
Operators
Arithmetic
Logical
Comparison
Others
Variables
4. PROGRAM WRITING
Creating an application
Compilation
Debugging
Testing
Execution
5. CONTROL STRUCTURES
Types of control structures
Definition
Types:
Sequence
Selection
Iteration / repetition
Implementation of data structures
6. ERROR HANDLING
Types of errors
- Syntax
- Run time
- Semantics
- Logical
Error handling techniques .
Writing error handlers
On error resume
On error to go
Error object
Debugging tools
7. SUB-PROGRAM
Meaning of sub-program
Types of sub-programs
Private sub program
Public sub-program
Scope of variables
Local variables
Global variables
8. Data structures
Data structures
Types of data structures
- Arrays
- Records
- Pointer
- Stacks and queues
- Sets
- Files
Sort Techniques
- Bubble shell
- Selection
Search Techniques
- Binary search
- Linear search
9. Linking to databases
- Database controls
- Data control
- Ms data bound controls
- Active data object (ADO)
Reports
Data reports
10. Emerging Trends In Visual Basic.
Emerging trends in visual programming
Challenges of emerging trends in Visual Basic
Coping with challenges of emerging trends in visual programming.
Content
1. Introduction to visual Basic 6.0
Visual Basic
It is a programing language and development environment that allows you to create programs
that run under windows Os. With VB you can create programs that interact with the
Databases, interact with internet and even with hardware.
Event Driven Programing
V.B is event driven ,meaning the code remains idle until called upon to respond to some
event. An event can be a mouse click, a key press , menu selection e.t.c . V.B is governed by
an event processor. Nothing happens until an event is detected .Once an event is detected the
code corresponding to that event (event procedure) is executed.
Terminologies
a)Forms
Are windows that you create for user interface .A form generally has many different controls
placed upon it.
b) Controls
Are graphical features drawn on forms to allow user interaction, examples are textboxes
labels, scrollbars command buttons e.t.c. Forms and controls are sometimes collectively
known as objects.
c) Properties
Every characteristic of a form or control is specified by a property, examples of properties
include name, caption ,size, colour ,position and content.
d) Methods
Is a built-in procedure that can be invoked to impart some action to a particular object e.g
print method. Example: Me.print sum ‘ displays value held by the variable sum in the
current form.
e)Event Procedure
Is a code related to some object. This is the code that is executed when a certain event occurs.
f)General Procedure
Is code not related to objects. This code must be invoked by the application.
g) Module
It is a collection of general procedures, variable declaration and constant definitions used by
the application.
h)Application
Is a collection of objects that work together to accomplish something useful. In Vb the
application is called a project. A project could be the management of a video store ,
calculation of mortgages e.t.c
i)Object
Is a piece of s/w that has properties and functions that can be manipulated.
2. VISUAL OBJECTS
Visual Basic Integrated Development Environment (I.D.E)
I.D.E is a VB screen in which one can develop, run, test and debug applications. It contains
the elements with which you can develop the user interface of your application.
Elements/components/parts of IDE (Visual Objects)
1. Menu bar
It displays the commands you need to work with VB. Menus are provided for standard
actions like : file , edit , view , window and help and to access functions specific to
programming such as: project, format and debug
2.Standard Toolbar
The standard toolbar has the standard icons that are shortcut command to the menu bar
commands. They provide quick access to commonly used commands in the programing
environment.
3.Toolbox
It contains a set of tools that can be used at design time to place controls on a form
4.Project Window
This window lists the forms and modules in your current project.
5. Properties window
This window lists the property settings for the selected form or control. The properties are
characteristics of an object such as name, size, colour, caption e.t.c
6. Form layouts window
It shows where (upon program execution) your form will be displayed relative to your
monitor’s screen.
7. Code editor window
The code editor window is used for entering and editing the programing code for the
application. Each form has its own code editor window .By double clicking on an object the
corresponding code editor window will open.
8. Immediate , local and watch windows
This windows are included in the IDE for use in debugging your application. They are
available only when you are running your application.
Controls
Are graphical features drawn on forms to allow user interaction .it is a tool used to display
information or retrieve information from the user.
Control types
1. Standard controls
Are controls always present in the toolbox
2. Custom controls
Are brought into the VB environment when needed and they extend one tool box.
Picture box
Is used to display graphical objects or text and to initiate event actions. It is similar to an
image box but has more properties , redraw slower and cannot be stretched.
Label
Displays a text on a form. The text cannot be reassigned during program execution though its
appearance can be altered during the program execution though its appearance can be altered
Text box
Provides a means of entering or displaying text. The text may be already available or can be
entered during the program execution.
Frame
Used as a container of a group of controls
Command button
Used to activate an event driven procedure.
Check box
Used if more than one selection are to be made.
Option button
Are used when one selection must be made before an action is carried out.
Combo box
Is a special type of list box that combines the capabilities of a text box and a list box. It
provides a list of text item for selection by the user during program execution. Items can also
be added during program execution.
List box
Provides a list of text items for the selection by the user.
Horizontal scroll
Is used for drawing horizontal scrollbars on a form.
Vertical scrollbar
Is used for drawing vertical scrollbar on a form.
Timer
Allows timed events to occur repeatedly at a specific time interval
Drive list box
Provides a way of selecting a drive from a list of existing drivers
Directory list box
Provides a way of selecting a directory from a list
File list box
Provides a way of selecting files within a group of files .
Shape tool
Is used to draw ; circles, eclipses , squares and rectangles within forms
Line tool
Is used when drawing straight lines within forms.
Image box
Is used to display graphical objects
Data control
It provides a means of displaying information from existing database.
N/B :The number of tools available on the tool box depends on edition and release of VB
you are using.
Saving a VB project
Saving a VB project is different from other applications because VB operation involves
saving multiple files
a) To save a VB project for the first time, select the save project as command from the
file menu. The save file as dialogue box appear. You will have to enter a form name
and then click the same button ,the form is saved with an extension .frm
b) After this the save project As dialogue box appears. Type the name of the project and
it will be saved as file with extension .vbp
Opening an existing project
You can open a project when VB starts or from the file menu. To open a project during start
up from the new project dialogue box that appears when VB is starting, click the existing
tab. A list of existing projects will be displayed. If VB is already running close all other
projects then click open project command on the file menu. The open project dialogue box
appears from which you can select the existing tab
3. PROGRAM STRUCTURE
VB FUNDAMENTAL CONCEPTS
Data types
Data types Description
Integer A whole number with no fraction part. Integer range from -32768 to 32767
Long Numbers which are integers but have bigger values and range. They range
integer from -2,147,483,648 to 2,147,483,647
Single A single precision real constant includes a fractional part. The largest value is
3.4 x 1038
Double It includes a fractional part but has far much larger magnitude than the single
real number constant. However it cannot be larger than 1.2 x 10308
String Characters enclosed in quotation marks
Boolean Data types that have only two logical states i.e true or false
Constants
A constant is a value that remains the same. It does not change during program execution.
There are three types of constants; string, numeric and named constants.
String constants
Is a sequence of characters enclosed in quotation marks.They are used to write non-numeric
values like telephone numbers, addresses and names
Numeric constants
Are either whole numbers (integer), double or single
Named constants
Is identified by name rather than its actual values, const keyword is used declare this type of
constants
VARIABLES
A variable is a memory location referred to by name used to hold a value that is subject to
change during program execution. In VB the following rules should be followed when
naming variables:
1. The variable name must not have more than 255 characters
2. The variable name must start with a letter.
3. The letter case is not important when declaring variables
4. A variable name must not be a reserved word
5. Variable names should not have spaces.
A variable is declared using the reserved word DIM the short form of the word dimension
(size). It is used to associate a variable with a specific data type e.g Dim First_Name as
String means that the variable first_name is of the type string.
VARIANTS
Is a variable whose data types has not been explicitly declared by the program. They are
called variants because their data types keeps on changing with the values they hold
Scope 9lk
Refer to the level of the program that a variable, a constant or a procedure is recognized. The
scope of a variable constant is said to be global or local. The scope of the procedure, variable
or constant is set by declaring it as either private or public. The following terms are used in
this regard:
1. Private sub-procedure
2. Public
3. Global variables / constants
4. Local variables
A public procedure can be accessed from any module or form in the program while private
procedure is accessed in the module or form within which it is declared.
A variable or constant that is declared outside the standard module but within the same
project is said to be global.
User defined data types.
Is a data type whose individual components are standard data items
Using suffixes to declare variables and constants.
Suffixes are special symbols appended to the end of a variable constant name in order to
associate them with a particular data type
Examples
Suffix Data type Long Declaration Short declaration
% Integer Dim A as integer A%
! Single Dim X as single X!
$ String Dim A as string Q$
& Long integer Dim C as long integer C&
# Double Dim P as double P#
Operators
They include;
i. Arithmetic
ii. Relational
iii. Logical
Arithmetic operators
Are special symbols that are used to write arithmetic expressions.
i. Relational Operators
Is used in an expression that returns a true or false value when evaluated. The operators can
compare numeric variables, constants or expressions.
Operator Name
= Equal to
<> Not equal to
> Greater than
< Less than
<= Less than or equal to
>= Greater than or equal to
Logical operators
operator Operation
And Results in a condition that is true if both expressions are true
Or Results in a condition that is true if one of the condition is true or both are true
Xor Results in a condition that is true if one of the condition is true and the other is
false
Not Negates the value of a logic expression
Expression
Print format (16.778994, “##.##”) 16.78 (notice the rounding)
Print format (Now, “mm-dd-yyy”) 1-20-20105
Print Format (15678; “##,###.00”) 15,678.00
Label 1. Caption = Format$ (sprice, “#####.##”) 10,630.75
N/B: The dollar sign may be used with the format function depending on the type of output
required. In the last row of the table the formatted output is displayed on a label control.
Program comments
Comments are English statements included in the code to document a program. The
comments are not executed when the program is running. In Visual Basic, a comment starts
with a single apostrophe (‘) followed by the comment statement e.g X = Sin (P) ‘ find the
Sine of P and store it in X
4. PROGRAM WRITING
Project
Create a program that can be used to calculate the area of a rectangle. The program should
prompt the user to enter the length and the width of the rectangle .To create the project
proceed as follows;
1. Open visual basic and select standard .EXE from the new project dialog box. A blank
form will be displayed.
2. Place three text boxes and two command buttons. Double click the text box tool on
the tool box then command button. Add another command button .Use the shape tool
to place a rectangle on the form. Drag the controls to the desired location on the form
and repeat the process until you have the interface below.
3. The next step is to define the set of properties for each control. To do this, right click
on the control then click properties. Set each control in the properties window.
N/B: The conventional way of setting the name property of any object in VB is to use object
prefixes. Such as txt for text or boxes, lbl for labels cmd for command buttons etc.
4. After setting the properties, we can now write the event procedures that calculates the
area of the rectangle once values are entered in the txtlength and txtWidth textboxes.
To write the code double click calculate button and write the code listing below.
Declaration of variables
There are two ways of declaring variables
i. Explicit declaration
The variable is declared in the declaration section of the program or at the beginning of a
procedure e.g
Dim A As integer ‘explicit declaration’
Dim name as string ‘ explicit declaration.
ii. Implicit declaration
The variable is declared on the fly. Its data type is deduced from the declaration of other
variables e.g
Dim A as integer ‘ explicit
Dim B As integer ‘explicit
C = A + B ‘Implicit declaration.
Project Examples
Example
Calculation of area of a rectangle, length and Width entered by the user.
a).User Interface/UI
Frmarea
Calculation of area
Enter width
Txtwid
Area is
Txt A
Exit calculate
calculate
cmdexit cmdcalculate
b).Code
Private sub cmdexit_click()
End
End sub
Private sub cmdcalculate_click()
Dim L as integer
Dim W as integer
Dim A as integer
L =val(txtlen.text)
W = val(txtwid.text)
A = L*W
TxtA.text = str (A)
End sub
Example
A Vb program to accept the radius of a circle, calculate and display its area
a).UI
FrmArea
Area calculation
TxtR
Enter radius
Area is TxtA
Compute
Cmdcompute
b).Code
Private sub cmdcompute_click()
Dim R as single, Area as single
Const pie as single = 3.142
R = val (txtR.text)
Area = pie * R * R
TxtA.text = Str(Area)
End sub
Example
Project on calculation of sum of two numbers
Frmsum
Summation of numbers
Txtnum1
Enter num 1
Exercise
Write a VB that accept the height and radius of a closed cylinder, compute and display its
surface area. Attach your code to a command click event.
Private sub cmdsurfacearea_click()
Const pie as single = 3.142
Dim height as integer, radius as integer
Dim surfaceArea as single
height = val(txth.text)
radius = val (txtr.text)
SurfaceArea = 2 * pie * radius * radius + (pie *2*radius * height)
Lblarea.caption = surfaceArea
End sub
Frmsarea
Surface area
Txtr
Enter radius
Txth
Enter height
Lblarea
Surface area is
CALCULATE Cmdsurface
CONTROL STRUCTURES
a. Selection control structures
i. If…..else construct
Used to write programs that require branching depending on a test on some condition.
-Syntax is:
If (condition) then
Statement(s)
Else
Statement(s)
End IF
Example
A program 2 accept two numbers and determine the greatest
a) .User interface
Frmcompare
Comparison
Txtnum1
Enter first num
txtnum2
Enter second num
picresult
cmdcompare
Clear Compare
cmdclear
If with Else If
Used in situations where we have more than one condition to test in the program.
-Its Syntax is:
If (condition1) Then
Statement1
Else if (condition2) Then
Statement2
Else if (condition3)
Statement3
:
.
Else
StatementN
End if
Example
A program to accept student position in class and display category as per the table below
Position Category
1-3 Top 3 student
4-5 Top 5 student
6-10 Top 10 student
a) User interface
Frmcategories
Categorize
txtPos
Enter position
picResult
cmdcategorize
categorize
a).User interface
Frmgrade
Grade marks
txtmarks
Enter marks
picresult
GRADE cmdgrade
OPTION BUTTON
-Control used to make a single selection out of several options available.
VALUE PROPERTY
The value property is used to indicate whether the option button is selected or not.
A value property of TRUE means the option button is selected and a value property of
FALSE means no selection made.
PROGRAM EXAMPLE:
Program to prompt user to enter principal amount, calculate and display interest based on the
gender selected. The criteria for interest rates are given in the table below.
txtA
optmale
optfemale
PicResult
cmdCompute
b).Code
CHECKBOX
-Control used to make more than one selection out of several options available.
VALUE PROPERTY
The value property is used to indicate whether the checkbox is selected or not.
A value property of 1 means the checkbox is selected and a value property of 0 means no
selection made.
PROGRAM EXAMPLE:
Program to prompt user to enter salary earned, calculate and display tax based on the status
selected. The criteria for tax rates are given in the table below.
txts
chkM
chkS
PicResult
cmdCompute
b).Code
Example
A program to accept the position of a student in a class and display his category as per the
table below.
Position Category
1-3 Top 3 students
4-5 Top 5 students
6-10 Top 10 students
a).User interface
Frmposition
Determination of category
txtpos
Key position
picresult
cmdcategory
Categorize
b).Code
Exercise
1. Rewrite a program to grade marks using the case construct
2. Write a vb program that accepts the initals of the color and display its name in full as
per table.
Initials Colour name in full
R Red
B Blue
G Green
a).User interface
Frmcategorize
Categorize
picresult
Determine
cmddetermine
b).Code
private sub cmddetermine_click()
dim marks as integer
marks =val(txtmark.text)
SELECT CASE marks
Case 70 to 100
Picresult.print ”A”
Case 60 to 69
Picresult.print “B”
Case 50 to 59
Picresult.print “C”
Case 40 to 49
Picresult.print”D”
Case 0 to 39
Picresult .print “F”
Case else
Picresult.print”You entered invalid marks”
End select
End sub
Example
A program to display numbers 1 to 5
a).UI
Frmdisplay
Display numbers
picdisplay
cmddisplay
b).Code
Private sub cmddisplay_click()
Dim I as integer
For I = 1 to 5
Picdisplay.print i
Next i
End sub
Example 2
A program to find sum of three numbers entered by the user.
Frmsum
Add numbers
picresult
cmdsum
b).Code
Private sub cmdsum_click()
Dim I as integer
Dim sum as integer
Dim num as integer
Sum = 0
For I = 1 to 3
num = inputbox (“ Key in number”, “ addition”)
sum = sum + num
Next I
Picresult print “sum of numbers =”, sum
End sub
3. Do 4. Do
Statements (s) Statements(s)
Until (condition) While (condition)
-With loops 1 and 2 the condition is tested before the statements inside the loop are
executed
-With loops 3 and 4 the statements are executed at least once before the condition is
tested.
b).While loop
-It syntax is:
While (condition)
Statement(s)
Wend
-Exactly the same as the Do while..Loop, and as with the Do while..loop, the
While..Wend loop executes statements inside it as long as the condition set is true.
Example
Program using while..wend loop that displays the number series:
3,7,11,15
a).UI
Frmdisplayseries
Display series
picdisplay
cmddisplay
b).Code
Private sub cmddisplay_click()
Dim num as integer
num=3
While (num<=15)
Picdisplay.print num
num=num+4
Wend
End sub
Example:
A program tha accepts and calculates the sum of two numbers using a sub procedure.
a).User interface
frmProcedureadd
Addition procedure
Txtn 2
Enter num2
Sum is Txts
Add cmdadd
b).Code
Private sub cmdadd- click
Dim x as single, y as single
X = val(txtn1.text)
Y = val(txtn2. Text)
Call add(x,y)
End sub
Private sub add (n1 as single, n2 as single)
Dim S as single
S = n1 + n2
Txts.text = str(S)
End sub
-Sub procedures make a program easy to read, modify and debug. Sub procedures can
also be called several times during the execution of the program.
a).UI
frmtrapeziaArea
Trapezia Area
Enter Height
H txth
picresults
Compute cmdcompute
b).Code
private sub cmdcompute()
Dim area as single
a = val (txta. Text)
b = val (txtb. Text)
h = val (txth.text)
call procdisplay()
call CalcArea(a,b,h)
End sub
private sub procdisplay()
picresults.Print ”This program calculates area of Trapezium”
End sub
PARAMETER PASSING
PASSING A VARIABLE BY REFERENCE TO A SUB PROCEDURE
Suppose a variable call it arg appears as an argument in a call statement and its
corresponding parameter in the sub statement is par.After the sub procedure is
executed, arg will have whatever value par had in the sub procedure hence not only is
the value of arg passed to par but the value of par is passed back to arg.
Example
Private sub cmddisplay-click()
Dim amt as single
picresult.cls
amt = 2
picresults.print amt;
call triple (amt)
picresult.print amt;
End sub
Private sub triple (byref num as single)
picresult.Print num;
num = 3 *num
picresult.print num;
End sub
Output
2266
-It provides a vehicle for passing values form a sub procedure back to the place from
which the sub procedure was called. The variable amt is said to be passed by
reference.
Scope of variables
a)Local variables
when thesame variable name appears in two different sub procedures or sub procdure
and an event procedure, visual basic gives the variable separate identities and treats
them as two different variables. A value assigned to a variable in one part of the
program will not affect the value of the other like named variable in the other part the
program, unless of course the values are passed by a call statement. Also each time a
sub procedure is called, all declared variables that are not parameters assume their
default values(numeric variables have default value 0 and string variables default is
empty).
Example
Private sub cmddisplay – click()
Dim x as single
‘Demonstrate the local value of variables
Picresults.cls
X=2
Picresults.print x
Call trivial
PicResults. Print x
Call trivial
PicResults. Print x
Call trivial
PicResults,Print x;
End sub
Out put
2032032
Output
Sum of 2 and 3 is 5
Num1 = 3
Num2 = 4
FUNCTIONS PROCEDURES
A function is simply a general procedure that returns one value to the funtionc that calls it.
Although the input can involve several values, the output always consist of a single value.
The items inside the parenthesis can be constants, variables or expressions. Function
procedures are defined by function blocks of the form:
The variables in the top line are called parameters and variables in the function block that are
not parameters have local scope. Function names should be suggestive of the role performed
and most conform to the rules for naming variables.
Example of function procedures
Private function FtoC (t as single) as single ‘convert Fahrenheit temperature to Celcius
F toC = 5/9 *( t – 32 )
End function
Example
The following program uses the function FtoC to convert a Fahrenheit temperature to
Celcius temperature.
a).UI
Frmconvert
Convert F to Celcius
Frmconvert
piccelcius
CONVERT cmdconvert
b).Code
Private sub cmconvert – click()
Dim Celcius As single
Dim f as single
f = val(txtf.text)
Celcius=FtoC(f) ‘call the function FtoC
Piccelcius.print “celcius temp is “, Celcius
End sub
Hypotenuse calculation
Enter Height
picHyp
Compute cmdcompute
Code
Private sub and compute and click( )
Dim a as single, Hyp as single
Dim b as single
a = val (txth. Text)
b = val (txtb. Text)
Hyp = Hypotenuse (a, b)
Pichyp.Print “Hypotenuse is “, Hyp
End sub
Exercise
Write a VB program using a function that accepts the dimensions of a closed cylinder,
calculates and returns its surface area for display.
DATA STRUCTURES
Arrays
Is a data structure that stores several data items of the same type. The figure below shows
how data of type integer is stored in an array.
20 30 80 120 200 250
index 0 1 2 3 4 5
The array has cells. The numbers 0 to 5 are called array indices or subscripts. In V.B
an array starts from cell 0 as shown in the table.
frmdisplay
Display
picdisplay
cmdDisplay
DISPLAY
b).Code
Private sub cmdDisplay – click( )
Dim A(4) as integer
Dim i as integer, j as integer
For i = 0 to 4
A (i) = inputBox (“enter array value” ,“arrays”)
Next i
For j = 0 to 4
Picdisplay.Print A(j)
Next j
End sub
Example
A VB program to prompt user for an array of 3 integer elements, compute and display
their sum
a).UI
frmsumarray
Sum array
Picsum
cmdcompute
COMPUTE
b).Code
Private sub cmdcompute _click()
Dim num (1 to 3) as integer
Dim i as integer, sum as integer
Sum = 0
For i = 1 to 3
Num (i) = InputBox (“enter array value,”Array”)
sum = sum + num(i)
Next i
Picsum.Print “sum of values is “, sum
End sub
Exercise
Rewrite example 1. On arrays so that elements are displayed in reverse in which they
are inputed.
2. Rewrite example 2 so that the average of the three inputed array values is also
computed and displayed.
Code
Dim num (1 to 3) as interger private sub cmdcalculate – clicki) dim I as integer, sum
as integer
Dim average as integer
Sum= 0
For I = 1 to 3
Num (i) = input Box (“enter array value”, arrays”)
Sum = sum + num(i)
Next i
Average = sum/3
Picsum print “sum of value is “, sum
Picsum, print “average of value is “ average
End sub.
TWO DIMENSIONAL ARRAYS
A two dimensional array is a data structure in which elements are arranged in rows
and columns. Two subscripts are used to identify an item e.g score(2,4)
Means 3rd row 5thcolum this is because the array was declared as from row 0 as
follows:
Dim score (0 to 2, 0 to 4) as integer OR
Dim score (2, 4) as integer
0 1 2 3 4
0
1
2
3
4 Score (2,4)
Example
A program to accept an array of 4 marks from 5 different students, calculate and
display total marks for each student alongside the marks on the form in the format
shown below:
a).UI
frmmarks
Total marks
cmdcompute
COMPUTE
b).Code
Private sub cmdcompute_click ( )
Dim studmarks (1 to 5, 1 to 4) as integer
Dim student as integer, mark as integer, col As integer
Dim sum (1 to 5) as integer
Col = 1
Me.print ”math”, Eng”, Kisw”, “Science”, “Total”
For student = 1 to 5
sum (student) = 0
For mark = 1 to 4
studmarks (student, mark) = inputbox (“key in student marks’, “marks” )
sum (student) = sum(student) + studmarks(student, mark)
Me.print tab(col);studmarks(student, mark); ‘print information starting from column 1
col = col + 6
If col > 20 Then
Me.print tab(col);sum(student) ‘print sum of marks for student and begin newline
col = 1 ‘reset column to start printing next information from column 1
End if
Next mark
Next student
End sub
Exercise
1. Write a vb program to assign the value 65 to all the locations of a 4 x 4 array and
display them in a table as shown
65 65 65 65
65 65 65 65
65 65 65 65
65 65 65 65
2. Rewrite our previous example on two dimensional array so that the average mark
for each student is also computed and displayed alongside other values as shown.
Illustration of how the elements list of names are sorted in ascending order using bubble
sort(Illustration Page 193-VBA beginner how to…)
Example
A program to sort a list of 5 numbers assigned to an array in ascending order using bubble
sort.
a).UI
frmBubbleSort
Bubble Sort
picsorted
sort cmdsort
b).Code
‘General declaration
Dim num (1 to 5) as integer
Private sub cmdsort_click ( )
Dim pass as integer, compare as integer, temp as integer
dim i as integer,
for pass = 1 to 5
for compar = 1 to 4
If num(compar) > num(compar+1) Then
temp = num(compar)
num(compar) = num(compar+1)
num (compar+1) = temp
End if
Next compar
Next pass
Picsorted.print ”sorted elements are : “
For i = 1 to 5
Picsorted. print num(i)
Next i
End sub
SHELL SORT
The bubble sort is easy to understand and program. However it is too slow for long lists.
The shell sort is much more efficient in such cases. It compares distant items first and works
its way down to nearby items. The interval separating the compared items is called the gap.
The gap begins at one-half (½) the length of the list and it is successfully halved until
eventually each item is compared with its neighbor as in the bubble sort. The algorithm for a
list of n items is as follows:-
1. Begin with a gap of g = int (n/2)
2. Compare items 1 and 1 + g, 2 and 2 + g , ----- n-g and n ,swap any pairs that are out
of order
3. Repeat step two until no swaps are made for gap g.
4. Halve the value of g
5. Repeat step 2,3 and 4 until the value of g is zero .
The shell sort is illustrated below. The elements are sorted in ascending order, crossing
arrows indicate that a swap occurred.
Elements to be sorted are names: pebbles barney William, Fred, Dino
Initial gap = int (num of items/2) = int(5/2) = 2
Because there was a swap, use the same gap for the second pass.
There were no swaps for the current gap of 2, so Next Gap = Int([Previous Gap] / 2) = Int(2 / 2) = 1
Because there were no swaps for the current gap, then Next Gap = Int([Previous
Gap] / 2) = Int(1 / 2) = 0 and the Shell sort is complete.
Notice that the Shell sort required 14 comparisons to sort the list whereas the bubble sort
required only 10 comparisons for the same list. This illustrates the fact that for very short
lists, the bubble sort is preferable; however, for lists of 30 items or more, the Shell sort will
consistently outperform the bubble sort.
Example
Program that sorts a list of five integers in ascending order using shell sort
a).UI
frmShellSort
Shell Sort
picsorted
sort cmdsort
b).code
‘General declaration
Dim num (1 to 5) as integer
const n as integer = 5
Private sub form _load( )
‘Read the numbers into array
num (1) = 60
num (2) = 90
num(3) = 40
num(4) = 30
num(5) = 80
End sub
Selection sort
In selection sort the item in the 1st position is compared with the other elements. If the
elements being compared are not in order they are swapped.
Illustration on how the elements 9, 6, 2, 10 are sorted in ascending order
9 6 2 2
6 9 9 9 1st pass
2 2 6 6
10 10 10 10
2 2 2 2 2
6 9 9 9 9
10 10 10 10 10
Example
A program to sort a list of five names in ascending order using selection technique.
a).UI
frmSelectionSort
Selection Sort
picsorted
sort cmdsort
‘General declaration
Dim name (1 to 5) as string
Private sub cmdsort_click()
Dim passnum as integer, compar as integer
For passnum = 1 to 4
For compar = passnum + 1 to 5
If name (passnum) > name (compar) Then
Temp = name(passnum)
Name (passnum) = name(compare)
Name (compar) = temp
End if
Next compar
Next passnum
For i = 1 to 5
Picsorted.print name (i)
Next i
End sub
SEARCHING TECHNIQUES
1.Linear search/ sequential search
Compares the key (element being searched) successively with the elements in the search list.
If a match is found the program reports that the element is in the list( i.e found) otherwise the
program reports that the element is not in the list(i.e not found).
Example
A program to search for an element from an array
a).UI
frmLinear
Searching
picresult
sort cmdlinearsearch
b).Code
2. Binary Search
Works on a sorted list,
i. Divides an array by half by finding the middle element in the array i.e middle
element = first + last/2
ii. It then compares the middle element with the key.
a. If the middle element is greater than the key then the last location is computed by
last =middle -1 and search proceeds to the first half of array.
b. If the middle element is less than the key then the new first location is computed by
first = middle + 1 and search proceeds to the second half of the array.
c. If the middle element is equal to the key the search is over and the program reports
that the element is in the list otherwise program displays that the element was not
found.
Example
A program to search for an element from an array
a).UI
frmBinarysearch
Searching
picresult
sort cmdsearch
b).code
dim list(1 to 5) As integer
private sub cmdsearch _(Click)
dim key as integer, flag as boolean
key = inputbox (“enter value to search”,”search”)
dim first as integer, middle as integer
dim last as integer
flag = false
first = 1
last = 5
Do while (first <= last) and (flag = false)
middle = int((first + last )/2)
Select case list(middle)
case is = key
flag = true
case is > key
last = middle-1
case is < key
first = middle + 1
End select
Loop
If (flag=true)Then
picresult.print ”found”
else
picresult.print “not found”
end if
End sub
FILES
SEQUENTIAL FILES
Creating sequential files
1. Choose a file nam.A file name contain up to 255 characters consisting letter, digits
and a few other assorted characters but including spaces and periods
2. Choose a number from 1 through 511 to be the reference number of the file, while the
file is in use it will be identified by this number
3. Execute the statement open “filespec” FOR OUTPUT AS #n. where n is the
reference number. This process is referred to as opening a file for output .It allows
data to be output from computer and recorded in the specified files.
4. Place data into the file with the write#n statements e.g if a is string then the statement
write #n, a writes the string surrounded by quotation marks into the file.
If c is a number then the statement write #n, c writes the number c without any
leading or trailing spaces in the file number.
5. After the data has been recorded in the file, execute close # n whenever n is the
reference number. This statement breaks the communication link with the file and
dissociates the number n from the file
Example
The following program illustrates the different statements of the write statement. Notice the
absence of the leading & trailing spaces for numbers and the presence of quotation marks
surrounding strings
a).UI
Create Cmdcreatefile
b).Code
Private sub cmdcreatefile_click()
Dim name1 as string, name2 as string
Dim num as integer
Num = 80
Name1 = “Eniac”
Name2 = “Mauldily”
Open “C: \pioneer.txt “ for output as # 1
Write # 1, “Eniac”, 1946, num
Write # 1,1946, name1, name2
Write #1, 14*139, “J.P” & name1, name2,”joe”
Close #1
End sub
N/B : If an existing sequential file is opened for file mode output. The computer will erase the
existing data and create a new empty file.
Cmdcopyfile cmdcreatefile
search Display
Create
Copy to file
b).Code
Private sub cmdcreatefile_Click()
Dim intmsg as integer
Dim num as integer , i as integer
Open “C : \numberlist.txt” for append as #1
Intmsg = msgbox (“numberlist.txt opened successfully”)
For num = 1 to 6
i = Inputbox (“enter number to store in file “)
Write # 1,i
Next num
Intmsg=msgbox(“numberlist.txt closed”)
Close # 1
End sub
Example
Displaying contents of a sequential file (program)
Notes:
Open “number.txt” for input is #1
Input mode - opens an existing file for a read operation
Put #n, r, recVar where recVar is the record variable from Step 1.
Example
The following program creates and writes records to the random access file known as
colleges.txt
Add Done
cmdadd
‘module.BAS
Public type collegeData
nam as string *30
state as string*20
yrfounded as integer
end type
‘general declaration
Dim recordnum as integer
Private sub cmdadd_click()
dim college as collegeData
college.nam=txtcollege.text
college.state = txtstate.text
college.yrfonded = val(txtYrfounded.text)
recordnum = recordnum+1
put #1 ,recordnum,college
txtcollege.text =””
txt y founded.text = “”
txtcollege.setfocus
End sub
picoutput
txtR
txtN
Cbogender
cmdsave
adostudent
cmdclear
cmdaddnew
cmddelete
cmdF
List1
cboreg
txtn
txtg
Adogetstud txtp
txtb