Visual Basic 6.0 Class Notes

Introduction
Steps to Creating a Program
System Development Lifecycle
Visual Basic IDE
Controls/Objects
Object Naming Conventions
Object Properties
Object Methods
Object Events
Adding Code to a VB Program
Outputting data
Internal Documentation
Variables and Data Types
Assigning Values to Variables
Arithmetic Operators
Constants
Inputting data

 

Selection - IF
Compound Selection
For...LoopDo...Loop
File Input and Output
Counting and Accumulating
Debugging
Built-In Functions (Numeric, Format,String)
Subprograms
Variable Scope
Form Load vs Form Activate
Message Box
Input Box
Arrays
Dynamic Arrays
Multidimensional Arrays
Searching
Sorting
Menus
Timer Objects
Moving Images(Animation)

What is Computer Programming?

A program is a set of instructions that guide the computer in carrying out a specific task. To write a program you need to have a programming language (software) such as: Visual Basic, Turing, Basic, Pascal, Fortran, Cobol, C, etc. These are English-like languages that humans can read, understand and write, however the computer can not understand these languages! In order for the computer to carry out the instructions, the program must be translated to a language the machine understands, called machine language and then executed. The programs we write in Visual Basic  are first translated by the VB software. When the statements in the original or source program are translated to machine language, called the object program, the program is said to be compiled and ready for execution

Why Write Programs

All the software we use on the computer are programs written to carry out various applications. Even DOS and Windows is a program (or set of programs) written as an interface between the user and the hardware. DOS and Windows are operating systems. Without one of them we would need to know a great deal more to communicate with, and manage the hardware components of the computer system. Windows is a software package that allows us to work in DOS without needing to understand all the built in commands. It makes the computer friendlier to use because the menus and icons replace the need to remember all the DOS commands.

There is software referred to as application software such as; word processors (MS Works/Word), spreadsheets (Works,Lotus,Excel), desktop publishing (Pagemaker, Ventura Publisher) , database programs (Access,dBASE, Paradox,) graphics programs (CorelDRAW, AutoCAD) and communications software (PCtalk, HyperAccess). These programs allow us to process information easily.

If information needs to be processed in a repetitive manner then programming a computer to carry out the task will make the job quicker and easier. 

Steps To Creating a Program:

Software refers to a collection of instructions, called a program ( VB calls them a project) that directs the hardware (monitor, keyboard, mouse, CPU etc.)

The first step in writing instructions to carry out a task is to determine what the output should be. The second step is to identify the data, or input, necessary to obtain the output. The last step is to determine how to process the input to obtain the output. Therefore, the problem solving process used will always consist of three steps:

  1. input
  2. processing
  3. output

When solving a computer problem, each assignment asks you to first create an IPO chart. IPO stands for input, processing and output. IPO charts are done before you start to code. IPO charts state the processing in a structured english, sometimes called pseudo-code. For example:

Create an IPO chart for a program that will allow a person to input an amount to be deposited in a bank account, the interest rate and the number of years the money will be left in the account. Print the amount of money in the account at the end of the time.

Input Processing Output
amount deposited
interest rate
number of years
final amount = amount deposited
repeat for the number of years
   final amount = final amount + final amount * interest rate
	  
final amount

Notice that the IPO chart 'explains' how to change the input to the output. All the inputs are used in the processing and the outputs are clearly calculated in the processing. The processing is structured and indented similar to VB programs but the language is more like 'normal' English than a programming language. Many VB details are not included, such as dim, end if, next, val, print, because they are 'understood' to be needed when you start to code.

System Development Lifecycle

When working in teams of programmers, or on large programming projects, it is important to stay organized. Many efficient programmers plan their programs using the system development lifecycle or SDLC. The step-by-step process is shown below:

Step Explanation How to..
Analysis Define and understand the problem Be sure you understand what the program should do, that is, what the input and output should be.
Design Plan the solution to the problem

Find a logical sequence of precise steps that solve the problem.Create the IPO chart, in this class.

A sequence of steps such as this is called an Algorithm. Three popular methods used to develop logical plans are flowcharts, pseudocode and top-down charts. These tools or methods will assist the programmer in breaking down a large problem into smaller tasks.

Choose the Interface Determine how the input will be obtained and how the output will be displayed - layout the form(s)
Development Code Create the form and translate the algorithm into a programming language. The program is written during this stage. Write comments inside the program that explain to other programmers what the code is doing.
Testing Test and Debug Locate and remove any errors in the program.
Implementation Install the working program on the user's computer and train the user Write documentation that is intended to allow another person to understand the program and train the user how to use the program.

This method of organizing a programming project is sometimes called the waterfall method, because the steps proceed from one to the next, like water falling down from step to step.

There are other project methodologies that exist such as:

All these methodologies are used to coordinate teams of programmers working on large projects. Each methodology has its strengths and weaknesses.

Visual Basic Programming Environment (IDE - Integrated Development Environment)

Controls/Objects

In VB, a program is started by drawing the user interface (the part of the program a user will see) on a form (the rectangular area with the grid marks in the center of the IDE). All the controls you can place on a form are in the toolbox, on the left side of the IDE. Controls you place on a form and the form itself are called objects.

Examples of objects:

The Toolbox contains the following standard controls:

When placing several controls on a form, use the commands on the Format menu to place and size the controls. First, drag the mouse around the controls to select them. Using the commands on the Format menu, you can then align or size the controls as necessary. Control properties can generally be set at either design time or run time

Here is a form with Label, TextBox and CommandButton controls

Label Control

A label is a graphical control used to display text. Because a label is a graphical control, the user cannot edit the text directly. The most common use for a Label control is to identify controls that do not have a Caption property, such as the TextBox control. You can also use the Label control to display text such as status messages and other program information.

For more information about label properties, methods, and events, see "Label Control" in Visual Basic Help and click on properties.

TextBox Control

You use a TextBox control to obtain information from the user or to display information provided by the application. Unlike information displayed in a label, the user can change information displayed in a text box.

For more information about the properties, methods, and events of the TextBox control, see "TextBox Control" in Visual Basic Help.

CommandButton Control:

A command button performs a task when the user clicks the button. You use a CommandButton control to begin, interrupt, or end a process. When clicked, a command button appears to be pushed in and so is sometimes called a push button. The most common event for a CommandButton control is the Click event

Object Naming Conventions

All objects you place on a form must be given a name, in this course. An object's name is used to refer to the object in your program code. You can assign any name to an object, but it is a good idea to adopt a naming convention and use it consistently throughout your programs.

The following table lists the standard naming conventions used in Visual Basic. Adopting these conventions makes it easier for others familiar with the standard naming conventions to understand your code.

Suggested Prefixes for Controls

Control Type Prefix Example
Check box chk chkReadOnly
Combo box, drop-down list box cbo cboEnglish
Command button cmd cmdExit
Directory list box dir dirSource
Drive list box drv drvTarget
File list box fil filSource
Form frm frmEntry
Frame fra fraLanguage
Horizontal scroll bar hsb hsbVolume
Image img imgIcon
Label lbl lblHelpMessage
Line lin linVertical
List box lst lstPolicyCodes
Menu mnu mnuFileOpen
MS Flex grid msg msgClients
Option button opt optGender
Picture box pic picVGA
Shape shp shpCircle
Text box txt txtLastName
Timer tmr tmrAlarm
Vertical scroll bar vsb vsbRate

Properties

Properties define the appearance and behavior of objects. Text, Caption, and Name are common examples of properties. Properties are the attributes you set or retrieve. Each object has a long list of properties. These properties are very important to making the screen look right and to making the program act right.

Setting Properties at Design-Time:

Design-time is the time when you are laying out your form and writing your program code. Most properties of any object may be set at design-time. When an object on the form is selected, the properties for the object are displayed on the right-side of the IDE. To change or set a property, simply type your desired change in the area next to the property name.

Examples of Label properties:

NB: We will never leave the names - Label1, Label2, etc - because these are not meaningful names and will be confusing.

We will use the suggested prefix (see above) and meaningful names so that others familiar with the standard naming conventions will more easily understand your code. Eg. change the name of Label1 to lblTitle

Examples of Form properties:

Changing Object Properties during Run-Time

When the user is running the program, this is called run-time. Any property of any object can be changed during run-time. The general form of commands to change object properties is:

objectname.property=value

Examples:

Methods

Methods are actions that an object can perform, such as move, hide, show itself, etc. Generally, methods are actions you want to perform.

Events

Events are actions the user can perfom, which objects can respond to, such as click, double-click, keypress etc.  An event is an action recognized by an object. Clicking a mouse or pressing a key are examples of events.

Some events include:

Activate     DragOver     Load

Change     GotFocus     LostFocus

Click     KeyDown     MouseDown

DblClick     KeyPress     MouseMove

DragDrop     KeyUp     MouseUp

Each object has its own set of events that it recognizes. The events listed do not apply to all objects. For example, a form can recognize either a Click or DblClick event while a button only recognizes a Click event.

Adding Code to a VB Program

Every VB object may have code (programs) attached to it. When the user clicks on the object, VB will execute this program. Double click on an object on the form at design-time to bring up its code window which looks like:

Private Sub objectname_Click()

End Sub

Your commands go in between Private Sub and End Sub.   Commands are the lines of code you type in order to get the program to perform as you desire.

Some sample lines of code include:

Auto List Members Feature:

When the name of a control or object is entered, the Auto List Members feature presents a drop-down list of available members (such as properties and methods).

When you type in the first few letters of the property name, the name is selected in the list. Pressing the TAB key enters the property in the code window. In addition to accelerating your typing, this option is helpful when you aren't sure which properties are available for a given control.

The Auto Quick Info Feature:

The Auto Quick Info feature displays the syntax for statements and functions. When you enter the name of a valid Visual Basic statement or function, the syntax is shown immediately below the current line with the first argument in bold, as shown in the following illustration. After you enter the first argument value, the second argument appears in bold.

Outputting Data

Information can be displayed to the user in a textbox. In your code you assign your output to the TEXT property of the textbox object.

Examples:

txtOutput.text = "hello there"

txtOutput.text = "hello" + " there"

txtOutput.text = "hello + name

txtOutput.text = "hello " + name + vbNewLine + "goodbye now"

txtOutput.text =  "hello " + name + vbNewLine
txtOutput.text = txtOutput.text + "goodbye now"

txtOutput.text = "my age is " + CStr(16)

txtOutput.text = Format(name, "!@@@@@@@@@")
 

Internal Documentation:

Internal documentation, also called comments, are English statements added to your program code that explains your program to other people, which the computer does not process. Adding comments to code makes it easier for someone else to determine what the code does. It also helps you to understand the code at some later date.

In Visual Basic there are two methods for adding comments to code. Visual Basic ignores anything following a single quote (')  or REM, so comments can be placed on their own line or at the end of a line of code.

You must add the following comments to your program in the 'General' section:

    1. question number
    2. name
    3. date
    4. purpose of the project.

Example:

  ' assignment : 4
  ' programmer : Frank Furter
  ' date       : Feb. 21, 2000
  ' purpose    : A program that calculates profit for a company by reading from a file the 
  '              revenue and expenses of a given 'file.
  

In each sub/end sub, you must include comments throughout the sub to explain the code.

To comment a section of your program, when you are testing a program and don't want some of the program to run, select the lines of text or code to be commented and click Comment Block icon on the Edit Toolbar.

To access the Edit Toolbar, click on View, then Toolbars and then Edit.

Variables:

A variable in computer programming is location in the computer's memory that will store a single value, which you give a name to. You can think of a variable as a storage box with a name:

This is the variable whose name is age and the value 16 is stored in the box. What is stored in this memory location can change; it can vary. You must name your variables so that your program can remember where you stored the information. In a machine's language these memory locations are numbered which can be very confusing for the programmer. In a high level language like Visual Basic, good programmers give meaningful names to their variables, such as 'age' to store an age, 'name' to store a name, 'address' to store an address. In doing this, programs become easier to follow. Variables like x and b can be used but it becomes more difficult to know what is stored in them and using meaningless names is poor programming style and should be avoided wherever possible.

Naming Conventions for Variables

Visual Basic insists that the name of a variable must begin with a letter followed by letters, numbers or the underscore. You cannot put any special characters such as spaces, hyphens, periods etc. in the variable name. You must also avoid using reserved words or command names like print, tab, var, etc These words are part of the Visual Basic  language and using them would confuse the processor.

Declaring Variables

It is good programming practice to declare all variables before they can be used in a program. We declare a variable to instruct the processor to set aside a location in memory for our use, to assign a name to the memory location and to inform the processor what type of data we wish to store there. A programmer in VB uses the keyword dim to declare a variable. There are several different types of data - integer, single, string and boolean.  String data consists of any alphanumeric characters, such as names, addresses, phone numbers. Numbers can be stored as string data if you do not wish the carry out mathematical operations on them.

Here are some declaration statements and what they do:

dim age as integer
This statement will set up a memory location called age to store an integer (a positive or negative number without decimals). In most computers an integer only requires 2 bytes of memory.
 
dim answer as single
This statement will set up a memory location called answer, to store real values (positive or negative numbers that contain a decimal portion). The common number of bytes used is four.
 
dim flag as boolean
This type of variable can only have two values true or false. A boolean variable could be represented by one bit.
 
dim name as string
This statement will set up a memory location called name, to store string data - data consisting of alphanumeric characters. Each location will have enough space set aside for up to 256 characters of string. (each character is one byte of information)

You can require that all variables be declared before they are used. You do that by placing the Option Explicit statement in the General Declarations section of the module. This ensures that misspelled variable names do not get automatically declared by VB - which can cause program errors that are difficult to find.

Data Types

Name

Type of Data Represented

Range

Size(bytes)

Integer

numbers without decimals -32,768 to 32,767

2

Long

numbers without decimals +/- about 2 billion

4

Single

numbers with or without decimals -3.4E38 to -1.4E-45 for negative values

1.4E-45 to 3.4E38 for positive values

4

Double

numbers with or without decimals -1.8E308 to -4.9E-324 for negative values

4.9E-324 to 1.8E308 for positive values

8

Currency

numbers with or without decimals +/- 922 trillion to 4 decimal places

8

String

special characters (i.e. #,_~),letters, words,addresses, phone numbers etc. approximately 2 billion characters are allowed

variable

Boolean

evaluates to True or False  

1

Assigning Values

Values can be assigned to a variable using the = sign. The variable name always appears on the left of the = sign. Whatever is on the right is evaluated and then stored in the variable. The right side may be a literal (such as "Devoy"), a numeric value (such as 18), an object property (such as txtName.text) or an expression (such as 3 + 1), or another variable.

Arithmetic Operators

Parentheses should be used when necessary to clarify the meaning of an expression.  When no parentheses are used, normal BEDMAS rules apply.  VB has designated  certain symbols to represent certain mathematical operators.  See table below for details:

Operator

Symbol

Code

Output

Addition

+

3 + 4 7
Subtraction

-

7 - 4 3
Multiplication

*

4 * 7 28
Division

/

25/5 5
Integer Division

\

7\2 3 - rounds to the lowest integer.
Exponent

^

4^2 16
Parentheses

( )

(80 + 90 + 100)/3 90
Scientific Notation

E

4E-01

5.6E02

0.4

560

Constants

A constant is a meaningful name that takes the place of a number or string that does not change. Although a constant somewhat resembles a variable, you can't modify a constant or assign a new value to it as you can to a variable. VB has many predefined constants, these all start with vb___. User-defined constants are declared using the Const statement, in a manner similar to declaring variables. For example:

const PI as single = 3.141592
const TAX_RATE as single = 0.08

Constants are used to make your program more readable, since a name such as TAX_RATE provides more meaning than a number such as 0.08. They are also used when a value appears many times throughout your program - a change to the value of the constant must only be made in the declare, not the many places in your program where the constant is use.

To make others aware that a name is a constant, it is good programming practice to make the name all capitals, with individual words separated by an underscore.

Inputting Data

On a form, input form the user is frequently accepted in a textbox object. The TEXT property of the textbox object contains the user input. After the user has typed their input into a textbox, they often are required to use the mouse to click a button. Your code can then assign the contents of the textbox object to an appropriate variable.

Examples:

dim name as string
name = txtName.text

dim age as integer
age = CInt(txtAge.text)

dim cost as single
cost = CSng(txtCost.text)

If Structure

Programs can make simple decision using an if structure. A structure is a block of code that works together.

General format is:

if <condition> then
      code if the condition is TRUE
else
      code if the condition is FALSE
end if

You replace the <condition> with some test that can be true or false, such as grade = 11

Note: the 'else clause' is not required when not action is to be performed when the condition is false.

3 - way or More Decisions

if condition1 then
      code for condition1 TRUE
elseif condition2 then
     code for condition2 TRUE
elseif condition3 then
     code for condition3 TRUE
else
     code for condition1 False and condition2 False and condition3 False
end if

Relational Operators

= equal to

< less than

> greater than

<= less than or equal to

>= greater than or equal to

<> not equal to

Note: two strings may be compared, or a string may be compared to a literal. In this case, the values are compared letter by letter, as you would list words in a dictionary. However, capital letters come before lower case letters (eg. "A" is less than "a"). To compare strings without the concern for upper and lower case, you may want to convert the strings to all capitals or lower letters prior to doing the compare (see UCase and LCase below).

Examples:

if userschoice = 6 then
     (some code goes here)
end if

if age > 13 then
     (some code goes here)
     (another line of code goes here)
end if

if age >= 13 then
     (some code goes here)
else
     (some other code goes here)
end if

if town = "Winchester" then
     (some code goes here)
elseif town = "Cambridge"
     (some other code goes here)
elseif town = "Kitchener"
     (some other code goes here)
else
     (some other code goes here)
end if

Note that the else clause may be omitted, when not needed.

Coding Conventions

The code within each subsection of the selection (IF) structue is indented one TAB, for clarity. Remember to always indent your programs for easier readibility.

Compound Selection Statements

At times we have a more complex condition than just one simple test to determine whether a portion of the program should be executed or not. In this case we must connect together multiple tests using the Boolean operators.

Logical (Boolean) Operators

A Boolean expression can be formed using the logical operators AND, OR and NOT. A logical expression joins two expressions and creates an expression that evaluates to either true or false.  When AND is used both expressions must evaluate to true for the entire condition to be consider true.  If OR is used, either one of the expressions  or both expressions must evaluate to true for the entire condition to be considered true.

If condition 1 AND condition 2 Then 
          Statements
Endif

If condition 1 OR condition 2 Then 
          Statements
Endif  

If NOT condition 1 Then 
          Statements
Endif 

Operator Hierarchy

The use of parentheses with logical operators improves readability: however, they can be omitted sometimes.
Visual Basic has a operator hierarchy for deciding how to evaluate expressions without parentheses which is:

  1. all arithmetic operations are carried out
  2. then all expressions involving >,< and = are evaluated to true or false
  3. then logical operators are next applied,  in the order:
    1. BRACKETS
    2. NOT
    3. AND
    4. OR

Examples:

if age < 18 OR grade = 12 AND weight > 100 + 10 then
  (some code goes here)
end if

if (heightA < heightB - 10 OR weight < 110) AND grade > 9 then
  (some code goes here)
end if

For Next Loops:

A loop is used to repeat a sequence of statements a number of times. When we know how many times a loop should be executed, a special type of loop, called a For…Next loop can be used. The For…Next loop designates a numeric value, called the control variable, tht is initialized and then automatically changes after each execution of the loop.

The For..Next loop takes on the following form:

For I = m to n
    Statement(s)
Next I

I = control variable
M = initial value
N = terminating value

Example 1: A Program that displays the first five numbers and their squares.

   Dim x As Integer
   For x = 1 To 5
         txtOutput.text = CStr(x) + Space(5) + CStr(x ^ 2)
   Next x 

In the above example, the control variable was increased by 1 after each pass through the loop. A variation of the For statement allows any number to be used as the increment. The statement

        For 1 = m to n step x

Instructs the next statement to add 'x' to the control variable instead of 1. The number x is called the step value of the loop.

Example 2: a program that that uses 0 as an intial number and requests an ending number and a step value as input from the user and then displays the numbers within that range.

dim x As Integer
dim ends As Integer
dim increments As Integer
ends = CInt(txtEnds.Text)
increments = CInt(txtSteps.Text)
For x = 0 To ends Step increments
    txtOutput.text = txtOutput.text + CStr(x) + vbNewLine
Next x

 

Nested Loops

The statements inside a For…Next loop or a Do Loop can consist of another For…Next loop. Such a configuration is known as a nested loop and is useful in repeating a single data-processing routine several times.

Example 3: A program that prints a multiplication grid 3 X 3

dim j As Integer
dim k As Integer

txtOutput.text = ""
For j = 1 To 3
	For k = 1 To 3
		txtOutput.text = txtOutput.text +  CStr(j) + " X " + CStr(k) + " = " + CStr(j * k) + Space(8)
	Next k
	txtOutput.text = txtOutput.text + vbNewLine
Next j 

Do Loops

A DO LOOP repeats a sequence of statements either While or Until a certain condition is true. A DO statement precedes the sequence of statements and a Loop statement follows the sequence of statements. The condition, along with either the word While or Until, follows the word Do.

The format for the DO LOOP is as follows:

Do While condition
     Statements
Loop

 Example 4: Write a program that displays the numbers 1 to 10 using a Do While

Dim num As Integer


num = 1
txtOutput.text = ""


Do While num <= 10
	txtOutput.text = txtOutput.text +  CStr(num) + vbNewLine
	num = num + 1
Loop 

 Example 5: Write a program that displays the numbers to 10 using a Do Until

Dim num As Integer


num = 1
txtOutput.text = ""


Do Until num >10
	txtOutput.text = txtOutput.text +  CStr(num) + vbNewLine
	num = num + 1
Loop

Example 6: Write a program that prints a message once the correct password is entered.

Dim password As String


txtOutput.text = ""


Do While password <> "HOOAH"
	password = InputBox("Please enter your password")
	password = UCase(password)
Loop

txtOutput.text = "Congratulations , you 've entered my server space."  

 

File Input and Output

To date, our data has been put into memory using assignment statements created by the programmer
(e.g. name = "Frank Furter", num = 5)

or we have assigned the contents of an object to a variable
(e.g. name = txtName.text, num = val(txtNumber)

These methods are sufficient for small scale applications but with large volumes of data and most real-world applications we need a better , more versatile and accessible way of storing data. The hard disk or floppy disk offers the solution. Data files stored on disk can be accessed by several programs for different purposes.

Why use a disk?


Non-programmers can use a program and modify the data on disk without knowing how to program, such as a student typing an essay in MS Word. Data on a disk may be accessed and modified many times, such as changes to an essay. Data on a disk may be used by many different programs, such as an essay created in MS Word used for input to a MS Publisher document.

Types of Disk-File Access


Your programs can access files in 2 ways

  1. sequentially
  2. randomly

A sequential file accesses information one record at a time, in the same order the records were written, this is like a cassette tape, where you must pass by the first 3 songs to get the the fourth song.

A random access file can be accessed in any order you want. This is like songs on a CD where you can jump to any song you want, in any order.

Processing a Data File

The following 3 tasks must be carried out when accessing a data file:

1) Open the data file
2) Process the records, as required by the program (either read or write)
3) Close the file

Example #1:Write a program that uses a file for input and displays what is read. The form should consist of a command button and a textbox. Use Windows' Notepad to create the file data.txt containing the following line.

Data.txt
4, High Street

Example: Programmer assigns values

Private Sub cmdDisplay_Click()

     dim schoolNumber as integer
	  dim street as string
	 
     txtOutput.text = ""
     schoolNumber = 4
     street = " High Street"
     txtOutput.text = "Mr. Devoy's house is located on " + CStr(schoolnumber) + street

End Sub

Example: User stores values on hard/floppy disk and data is read from the file

Private Sub cmdDisplay_Click()
   
        dim schoolNumber as integer
        dim Street as string

        txtOutput.text = ""
        Open "g:data.txt" for input as #1

        input #1, schoolNumber, Street

        txtOutput.text = "Mr. Devoy's house is located on" + CStr(schoolnumber) + street
        Close #1
   
   End Sub

File Input Notes:


The open statement takes the form OPEN "Filename" [for mode] as [#} filenumber

Making Data Files


When creating a data file using Notepad, the format is important if the data is to be read in properly:

One of the main applications of programming is the processing of lists of data. A Do loop is used to display all or selected items from lists, search lists for specific items, and perform calculations on the numerical entries of a list.

Example: User stores values on hard/floppy disk and all data is read from the file and displayed.

Create a file named data.txt with 5 names of friend (remember to enclose each name in quotes)

Private Sub cmdDisplay_Click()
   
        dim count as integer
        dim name as string
		
        txtOutput.text = ""
        Open "data.txt" for input as #1
		
		for count = 1 to 5
           input #1, name
           txtOutput.text = txtOutput.text + name + vbNewLine
		next count
		 
        Close #1
   
   End Sub

EOF Function

Often the amount of data in a file may vary, unlike the example above that had 5 names. Instead of a counted loop (for) the data in a file to be processed are often retrieved by a Do loop. Visual Basic has useful function, EOF that tells us if we have reached the end of the file from which we are reading. If a file has a reference number "1" then the function takes on the following form:

EOF(1)

Example 7: A program that displays the contents of a telephone directory. The names and phone numbers are contained in a file. The loop will repeat as long as the end of file is not reached.

   dim names As String
   dim phone As String
   
   Open "ex4.txt" For Input As #1
   Do While Not EOF(1)
      Input #1, names, phone
      txtOutput.text = txtOutput.text +  names + Space(5) + phone + vbNewLine
   Loop
   
   Close #1 

Example 8: A program that will search the telephone directory in the previous question for a name specified by the user. If the name does not appear in the directory, a message of notification will appear.

   dim names As String
   dim phone As String
   
   names = ""
   Open "ex4.txt" For Input As #1
   
   Do Until EOF(1) Or names = txtName.Text
      Input #1, names, phone
   Loop 
   
   If names = txtName.Text Then
      txtOutput.text = names + Space(5) + phone
   Else
      txtOutput.text = "Name not found"
   End If
   
   Close #1

Counters and Accumulators

A counter is a variable that is used to calculate the number of elements in lists.
An accumulator is a variable that is used to sum numerical values in lists.

Example 9: A program that counts and finds the value of coins listed in a file.

   dim numCoins As Integer
   dim sum As Single
   dim value As Single
   
   sum = 0
   numCoins = 0 
   
   Open "ex6.txt" For Input As #1
   
   Do While Not EOF(1)
      Input #1, value
      numCoins = numCoins + 1
      sum = sum + value
   Loop
   
   txtOutput.text = "The value of the " + CStr(numCoins) + " coins is " + CStr(sum) 

In this example, numCoins is the counter because with each iteration of the loop, we add one to its value, thus in the end, we have counted how many coins there were in the file.
In this example, sum is the accumulator because with each iteration of the loop, we add the value of the coin, thus in the end, we have added up how much all the coins are worth.

Note the pattern of the count and accumulation statements: the count and accumulator variable appears on both the right and left side of the equals sign!

Also, it is important to start the count and accumulator variables out at some value before we start the loop (in this case 0), this is called initializing the variables.

Debugging

Computer Programming Errors

Preparing a computer program to solve a problem requires you to be systematic and precise. What is more, a program that is less than correct is no use at all. You must redefine it until it is perfect. When you first prepare a program it might produce crazy answers. You must correct the program errors or bugs until it gives correct results on the test data that you feed it. You must give it a wide enough range of test data to ensure it always gives correct results. 

There are three types of errors:

  1. syntax errors
  2. run-time errors
  3. logic errors

A syntax error is one that violates the grammatical rules or syntax rules of the programming language. A syntax error will result in an error message you are typing your program, and so is easy to find and fix.

A run-time error is an error that occurs when the programming is running and some instruction is impossible for the computer to perform, such as division by zero. The program is stopped and you are given a message box that asks if you want to END or DEBUG. If you select DEBUG, then VB highlights the line of code with the error.

On the other hand, with a logic error the program correctly runs but performs the wrong task. These errors can only be found by examining the results and running the program with a variety of test data. The correcting of program errors is called debugging.

Setting a breakpoint

Setting a breakpoint allows you to stop the programs execution at the line of code where the breakpoint is added. To set a breakpoint, click the Margin Indicator bar next to the line of code. When in break mode, you can move the mouse over any variable name and the ToolTip box will appear giving the value of the variable. Once in break mode, you can click on the step into, step out or step over buttons on the debug toolbar to execute the program. To step into a procedure means to run it one line at time. To step over a procedure means to run it as a unit. To step out of a procedure means to run until it completes the current procedure and returns to the calling procedure.

Stop statement

The Stop statement is similar to a breakpoint, except that it remains a part of the code until removed. You add the word Stop in the code where you would like the program to stop executing when it is running.

Viewing the values of variables

Visual Basic 6.0 has a new feature whereby you can quickly view the value of variables. When the programs execution is paused, simply move the cursor over the variable names in the code. A tool tip box will appear with the current value of the variable. This really helps with debugging your program.

Adding the debug toolbar

Right click anywhere on the code and click on debug. A second method is to click on View, Toolbars and Debug.

Adding a watch

If you would like the program to stop execution when a particular variable attains a specific value you can add a watch. Place the cursor on the variable you would like to watch, right click and click on add watch. Now under the heading expression, add variable = watchExpression. For example, if you would like the program to stop execution when the integer variable I has a value of 5 then you would type in I = 5" in the expression input box. Now click on the Watch Type of A Break when Value is True@. Now when intI has a value of 5, the program=s execution will break.

N.B. Watch expressions are not saved with the code.

The following codes appear beside the variable in the watch window. The code depends on the Watch Type.

Watch Expression

Break When Value is True

Break When Value Changes

Immediate Window (when in Break mode)

Whenever you are in break mode, you can print the value of any variable in the immediate window. Simply type print variableName and press enter in the immediate window. If the immediate window is not visible, simply click View and Immediate Window. For example, to print the value of the variable intLoanPayment simply type print intLoanPayment or ? intLoanPayment. When you press enter, the value of the variable will be displayed. The program must be running and in break mode for the immediate window to function.

Immediate Window (without using Break mode)

You can add code to your program to display the value of variables in the immediate window without having to add break points. Simply use the Debug.Print command in the code. For example, to display the value of dblLoanAmt in the immediate window add the following code to your program wherever you would like the value displayed:

Debug.Print ALoan Amount = A & dblLoanAmt

This is a quick method to check the value of variables without having add break points. The output is in the immediate window which does not interfere with the form the user sees.

Changing values of variables in the immediate window

When in break mode, you can change the values of variables and then continue the execution of the program. For example, if you want to test the program when intI has a value of 255, then simply add the statement intI = 255 in the immediate window and then click continue and see how the program is affected.

Built-In Functions

A Visual Basic function is a built-in procedure that performs a specific job and returns a value that can be used in expressions.  It is called "built-in"  because Visual Basic already contains the code that performs the task.  These functions are shortcuts that you can use instead of writing your own code.  

Functions associate a single value called output with one or more values called  input. The function is said to return the output value.

Built-In Functions may be categorized as follows:

Other functions are shown in the table below (n represents a number or numeric variable):  

Function

Purpose

Examples

Output Value

Tab(n) used in print statements to move the cursor to position n and place spaces in all skipped-over positions

if n is less than the cursor position, the cursor is moved the the n th position  of the next line

Print "1234567890"

Print "Go";Tab(5);"Now"

1234567890

Go  Now 

Spc(n) used in a print statement  to generate spaces Print "Go";Spc(3);"Now" Go  Now
Space(n) a string consisting of n spaces "Go"&Space(3)&"Now" "Go   Now"
Rnd generates a random number between 0 and 1, not including 1

Rnd

0.132345678
Chr(n) displays the character with ANSI value n (n must be a whole number from 0 to 255)

Chr(97)

"a"

Format Functions

In the following table n represents a number or numeric variable. date String represents a date in a form such as month/day/year.

Function

Purpose

Examples

Output Value

Format(n,"Standard") converts numbers to string representations having two decimal places and commas every three digits to the left of the decimal point  Format(1/6,"Standard")

Format(-12345,"Standard")

0.17

-12,345.00

Format(n,"Currency") converts numbers to string representations with a leading dollar sign, two decimal places, commas every three digits to the left of the decimal point, and encloses negative numbers in parentheses  Format(2000,"Currency")

 

Format(-0.2,"Currency")

$2000.00

 

($0.20)

Format(n,"#,0") rounds numbers to whole numbers and places commas every three digits to the left of the decimal point  Format(-10002.8,"#,0")

-10,003

Format(n,"Percent") converts numbers to string representations of the numbers in percent with two decimal places and a trailing percent sign Format(0.281,"Percent")

28.10%

Format(n,"Scientific") converts numbers to string representations of numbers in scientific notation  with decimal places Format(-0.018,"Scientific")

Format(-1018,"Scientific")

-1.80E-02

"-1.02E+03"

Format(n,fmt)

Format(n,"@@@")

used with fixed-width fonts, such as Courier or Terminal, to display columns of numbers so that the decimal points are lined up Format(0.20,"@@@@@")

Format(17.25,"@@@@@")

0.20 

17.25

Format(dateString,
"LongDate")
returns a formatted version of the date  Format("3/17/00","Long Date") "Friday, March 17, 2000"

Format(str, "@@@")

Format(str,"!@@@")

formats a string to a fixed length, with ! the string is left aligned, otherwise right aligned Format("hi","@@@@@") "   hi"

 

Numeric Functions

Function

Purpose

Examples

Output Value

Sqr(n) calculates the square root of the number  n Sqr(16)

Sqr(2)

4

1.414214

Int(n) returns the greatest whole number that is less than or equal to the number n Int(16.01)

Int(16.967)

Int(-16.11)

16

16

-17

n Mod m

returns the whole number remainder when  n is divided by  m 15 Mod 4

-8 Mod 3

3

-2

Round(n,d) returns n rounded to d decimal places Round(7.666, 1)
7.7

String Functions

In the following table n and  m represent numbers or numeric variables, str represents a string or  string variable.      

Function Purpose Examples Output Value
+ (or &) concatentation - glue together 2 strings to create a longer string

dim first as string
sim last as string
dim fullName as string

first = "sam"
last = "jones"

fullName = first + last

samjones
Left(str,n) returns the string consisting of the leftmost n characters of str
If n is greater than the number of characters in str, the value of the function is str.
Left("visual",3)

 

Left("basic",8)

"vis"

 

"basic"

Mid(str,m,n) returns a string consisting of n characters of str starting with the m'th character
If the parameter n is omitted, Mid(str,m) is all the characters from the m'th character on.
Mid("Mr. Devoy ",2,5)

 

Mid("Mr. Devoy",6)

"r. De"

 

"evoy"

Right(str,n) returns the string consisting of the rightmost n characters of str Right("Mr. Devoy",2) "oy"
UCase(str) changes all lowercase letters to uppercase UCase("Mr. Devoy") "MR. DEVOY"
LCase(str) changes all uppercase letters to lowercase  LCase("Mr. Devoy")  "mr. devoy"
Trim(str) removes all the spaces from the beginning and end of str Trim("  Mr. Devoy   ") "Mr. Devoy"
CStr(str) converts numbers to strings Str(8) "8"
String(n,str) returns the string consisting of the first character of str repeated n times String(5,"zebra") "zzzzz"
String(n,m) returns the string consisting of the character with ANSI value m repeated n times (m must be a whole number from 0 to 255) String(5,97) "aaaaa"
Replace(str,find,replace) returns a new string with all occurences of find changed to replace replace("hello there","e","i") "hillo thiri"

 

String-Related Numeric Functions

In the following table n represents a number or numeric variable,str,str1,str2 represent strings or string variables.      

Function

Purpose

Examples

Output Value

Len(str) the number of characters in the string str Len("Mr. Devoy")

10

InStr(str1,str2) The value of the function InStr(str1, str2) is the position of str2 in str1. InStr("function","o")

7

Val(str) used to convert strings to numbers, if the leading characters of str correspond to a number then Val (str) will be the number represented by these characters Val("4")

 

Val("4 High St.")

4

 

4

Asc(str) returns the ANSI number corresponding to the first character of str Asc("a")

97

Chr(int) returns the single character corresponding to the ANSI value of int (reverse of Asc) Chr(97)
a
CInt(str) converts a value in a string variable to an Integer variable type CInt("97") 97
CSng(str) converts a value in a string variable to a single variable type CSng("97.5") 97.5

Form Load and Form Activate

If you have code that you want executed automatically when a form comes up put the commands in:

Form Load - only executes when the form is first loaded. Note, this is very early in the running of your program and controls, such as picture boxes, may not exist yet, so can not have information placed into them.

Form Activate - executes every time the form comes up.

Warning: most often you should place your code inside the button click command, you should not normally need to use these events.

Message Boxes

Pop-up message boxes are created by the MsgBox command in your programming.

Examples of message boxes:

 response = MsgBox (Amessage, vbconstant ,title)

where vbconstant can be one of many choices such as

HINT: Use the books online, click on the binocular icon and and type in msgbox to see the numeric values for all the constants. Alternatively, you can type in the word msgbox in your code window and press F1.

Using the Returned Value of message boxes

userschoice = MsgBox("Are you sure you want to quit?", vbYesNo, "Quit")

If userschoice = vbYes Then
        End
End If

The MsgBox returns a numeric value depending on what the user does and this number is stored in the variable userschoice. Again, the numeric value exists in built-in vbConstants.

Numeric Value vbConstant User's Action
1 vbOK Ok Button
2 vbCancel Cancel Button
3 vbAbort Abort Button
4 vbRetry Retry Button
5 vbIgnore Ignore Button
6 vbYes Yes Button
7 vbNo No Button

Input Box


Usually, a text box is used to obtain input described by a label. Sometimes we want just one piece of input and would rather not have a text box and label stay on the screen forever. The problem can be solved with an input box. The inputBox uses the following form.

  stringvar = InputBox(prompt, title)

 

Example:

   dim schoolNumber As Integer
   dim Street as String
   dim filename As String

   filename = InputBox("Please enter the name of the file", "Name of File")

   Open filename For Input As #1
   Input #1, schoolNumber, Street
   answer = MsgBox("Mr. Devoy's High School is located on" + schoolNumber + Street)
   Close #1

   answer = MsgBox("Thanks for checking out my program",vbOKOnly, "Good Bye")

Modular Code - Subprograms

A module is an assembly of one or more parts that can be treated as a single unit. Larger structures are then built from smaller modules (e.g. Ikea furniture, Stereo, and computer systems) are all modular because you build a complete system from a set of individually purchased components. These issues become more important now that programs are written by teams of people rather than by individuals.

 Why use Modular Code within our programs? 

 Subprograms /procedures

Call statements:
A subprogram, as the name suggests, is a program written separately from the main program. It is like a mini-program. Subprograms are accessed via a CALL statement. They are not restricted to particular data types or to returning values as functions are. (e.g. a function can only return one value and a built-in function like INT can only return an integer value)

Call AddNumber (num1, num2)

 Notice that the first Subprogram name, 'AddNumber' is uppercase to distinguish it from a variable.

Arguments:   
Inside the parentheses of a Call Statement are arguments which in this case are variables. (num1, num 2). They could also be constants AddNumber(2,3,) or expressions AddNumber(num1 + 2, num2 + 3).

Parameters:
Parameters on the other hand appear in the heading of a subprogram and

Private sub AddNumber (byVal num1 as single, byVal num2 as single)

Creating a Subprogram

    1. Select Add Procedure from the Tools menu
    2. Type in the name of the subprogram
    3. The word Sub should appear selected in the Type box. If not, click on the circle to the left of the word Sub
    4. The word Public should appear selected in the Scope box. Switch the selection to Private. A Public procedure is available to all forms, whereas a private procedure is only available to the form in which it was defined.
    5. A separator line and two lines of code have been added at the bottom of the code window. The first line says Private Sub SubName(), and the cursor appears on a blank line above the words End Sub.
    6. Type the statements of the subprogram into this window.

Properties of Procedures:

Variable Scope:

Local Variables

The main program and each subprogram has its own set of variables. This means that a variable used in the main program cannot be accessed by any of the Subs, and that variables used in the Subs cannot be accessed by the main program or any other Subs. These variables are said to be Local. This makes sense when you consider that much of programming today uses the team approach. There would be chaos if the variables in one sub could affect the values of variables in another sub.

Form-Level Variables:

Visual Basic provides a way to make a variable visible to every procedure in a form's code without being passed. Such a variable is called a form-level variable or global variable. Form-level variables appear at the top of the code window and are separated from the rest of the code by a horizontal separator line.

Sub Program Examples

   'Example 1:
   'A program that adds two numbers without the use of subprograms.
   
   Option Explicit
   
   Private Sub cmdAdd_Click()
      dim num1 As Single
      dim num2 As Single
      dim answer As Single
   
      num1 = 2
      num2 = 3
      answer = num1 + num2
   
      'Display the sum of two numbers
   
      picResult.Cls
      picResult.Print "This program displays a sentence"
      picResult.Print "identifying two numbers and their sum." 
      picResult.Print "The sum of"; num1; "and"; num2; "is";    answer
   End Sub

'Example 2: A program that adds two numbers and calls a subprogram to
'display the header

Option Explicit

Private Sub cmdAdd_Click()

dim numl As Single
dim num2 As Single
dim answer As Single

numl = 2
num2 = 3
answer = num1 + num2

picResult.Cls
Call ExplainPurpose
picResult.Print
picResult.Print "The sum of"; numl; "and"; num2; "is"; answer

End Sub

Private Sub ExplainPurpose()

'Explain the task performed by the program
picResult.Print "This program displays a sentence"
picResult.Print "identifying two numbers and their sum."

End Sub


'Example 3:
'A program that calculates the sum of two numbers and calls 2 subprograms
'1st sub displays header
'2nd sub adds/displays the sum of 2 numbers by passing the values from the
'main program to the sub program 'AddDisplay

Option Explicit

Private Sub cmdAdd_Click()

dim numl As Single
dim num2 As Single

num1 = 2
num2 = 3

picResult.Cls
Call ExplainPurpose
picResult.Print
Call AddDisplay(num1, num2)

End Sub

Private Sub ExplainPurpose()

'Explain the task performed by the program
picResult.Print "This program displays a sentence"
picResult.Print "identifying two numbers and their sum."

End Sub

Private Sub AddDisplay(byVal num1 As Single, byVal num2 As Single)

'Display numbers and their subs
dim answer as single
answer = num1 + num2
picResult.Print "The sum of"; num1; "and"; num2; "is"; answer

End Sub


'Example #4

'A program that calculates the sum of two numbers three times by including
'the numbers as arguments. Subprograms can be called an infinite number of
'times saving the programmer valuable time.

Option Explicit

Private Sub cmdAdd_Click()

'Display the sum of two numbers with the Add subprogram called several
' times.

picResult.Cls
Call ExplainPurpose
Call AddDisplay(2, 3)
Call AddDisplay(4, 6)
Call AddDisplay(7, 8)

End Sub

Private Sub ExplainPurpose()

'Explain the task performed by the program
picResult.Print "This program displays a sentence"
picResult.Print "identifying two numbers and their sum."
picResult.Print

End Sub

Private Sub AddDisplay(num1 As Single, num2 As Single)

'Display numbers and their subs
picResult.Print "The sum of"; num1; "and"; num2; "is"; num1 + num2

End Sub

 


'Example #5
'Calculates the sum of two numbers calling 3 subprograms
'1st sub explains purpose
'2nd sub gets two numbers inputted by the user
'3rd sub adds and displays the sum of two numbers.

Option Explicit

Private Sub cmdAdd_Click()

'Calculates the sum of two numbers calling 3 subprograms

dim num1 As Single
dim num2 As Single

picResult.Cls
Call ExplainPurpose
Call GetData(num1, num2)
Call AddDisplay(num1, num2)

End Sub

Private Sub ExplainPurpose()

'Explain the task performed by the program
picResult.Print "This program displays a sentence"
picResult.Print "identifying two numbers and their sum."
picResult.Print

End Sub

Private Sub AddDisplay(byVal num1 As Single, byVal num2 As Single)

'Display numbers and their subs
Dim answer As Single
answer = num1 + num2
picResult.Print "The sum of"; num1; "and"; num2; "is"; answer

End Sub

Private Sub GetData(byRef num1 As Single, byRef num2 As Single)

'Receives two numbers from the user.
num1 = Val(txtNum1.Text)
num2 = Val(txtNum2.Text)

End Sub


'Example #6
'Display the sum of two numbers calling 3 subprograms
'1st sub explains purpose
'2nd sub gets two numbers
'3rd sub adds and displays the sum of two numbers.
'Demonstrates that the arguments and parameters
'do not need the same names
'Add a string variable 'name' to show importance of type, order, number
'when passing data.

Option Explicit

Private Sub cmdAdd_Click()

dim num1 As Single
dim num2 As Single
dim names As String

picResult.Cls
Call ExplainPurpose
Call GetData(names, num1, num2)
Call AddDisplay(names, num1, num2)

End Sub

Private Sub ExplainPurpose()

'Explain the task performed by the program
picResult.Print "This program displays a sentence"
picResult.Print "identifying two numbers and their sum."
picResult.Print

End Sub

Private Sub AddDisplay(byVal name As String, byVal n1 As Single, byVal n2 As Single)

'Display numbers and their subs
Dim answer As Single
answer = n1 + n2
picResult.Print name; ", the sum of"; n1; "and"; n2; "is"; answer

End Sub

Private Sub GetData(byRef name As String, byRef first As Single, byRef second As Single)

'Receives the name and two numbers from the user.
name = txtName.Text
first = Val(txtNum1.Text)
second = Val(txtNum2.Text)

End Sub


'Example #7
'Display the sum of two numbers calling 3 subprograms
'1st sub explains purpose
'2nd sub reads the user's name and 2 numbers from a file
'3rd sub adds and displays the sum of two numbers.

Option Explicit

Private Sub cmdAdd_Click()

dim num1 As Single
dim num2 As Single
dim names As String

Open "c:\temp\subdata5.txt" For Input As #1

picResult.Cls
Call ExplainPurpose
Call GetData(names, num1, num2)
Call AddDisplay(names, num1, num2)
Close #1

End Sub

Private Sub ExplainPurpose()

'Explain the task performed by the program
picResult.Print "This program displays a sentence"
picResult.Print "identifying two numbers and their sum."
picResult.Print

End Sub

Private Sub AddDisplay(byVal name As String, byVal n1 As Single, byVal n2 As Single)

'Display numbers and their subs
Dim answer As Single
answer = n1 + n2
picResult.Print name; ", the sum of"; n1; "and"; n2; "is"; answer

End Sub

Private Sub GetData(byRef name As String, byRef first As Single, byRef second As Single)

'reads a name and 2 numbers from a file
Input #1, name, first, second

End Sub


'Example #8: Form Level Variables
'Display the sum of two numbers calling 3 subprograms
'1st sub explains purpose
'2nd sub reads the user's name and 2 numbers from a file
'3rd sub adds and displays the sum of two numbers.

Option Explicit

dim num1 As Single
dim num2 As Single
dim answer As Single
dim names As String

Private Sub cmdAdd_Click()
Open "c:\temp\subdata5.txt" For Input As #1
picResult.Cls
Call ExplainPurpose
Call GetData
Call AddDisplay
Close #1

End Sub

Private Sub ExplainPurpose()

'Explain the task performed by the program
picResult.Print "This program displays a sentence"
picResult.Print "identifying two numbers and their sum."
picResult.Print

End Sub

Private Sub AddDisplay()

'Display numbers and their subs
answer = num1 + num2
picResult.Print names; ", the sum of"; num1; "and"; num2; "is"; answer

End Sub

Private Sub GetData()

'reads a name and 2 numbers from a file
Input #1, names, num1, num2

End Sub

Arrays

A variable is a name to which the computer can assign a single value. An array variable is a collection of simple variables of the same type to which the computer can efficiently assign a list of values.

A variable mark would look like this:

mark
64

An array of 10 marks would look like this:

  mark
index
64 77 87 75 65 54 95 47 66 87
1 2 3 4 5 6 7 8 9 10

 

All the storage boxes are called mark and to tell one from another, each has its own number, called the index. So, an array is similar to a motel, the entire motel has one name and to distinguish between rooms, each has a number on the door. In each element of the array (room of the motel), we can store one number. In the example above, 64 is stored in the first element of the mark array.

Creating an Array

In Visual Basic we first must declare (create) an array (build the motel) before we try to store information in it. The command for doing this is DIM.

DIM mark(1 to 20) as single Creates an array called mark with elements 1 to 20 that stores singles
DIM age(0 to 15) as integer Creates an array called age with elements 1 to 16 that stores integers
DIM name(10) as string Creates an array called name with elements 1 to 10 that stores strings

Assigning Values to the elements in an Array

Mark(1) = 76 Stores the number 76 in the fist element of the array mark
Mark(3) = 87 Stores the number 87 in the third element of the array mark

Displaying values in an array
PicOutput.Print mark(1)

To assign 0 in every element in mark
mark(1) = 0
mark(2) = 0
mark(3 = 0
mark(20) = 0

OR
for x = 1 to 20
     age(x) = 0
next x

To read from a file 20 marks and store in an array

Open "G:\marks.text" for input as #1
For x = 1 to 20
     input #1, mark(x)
Next x
Close #1

To read from a file with an unknown number of record

Open "g:\marks.txt" for input as #1
count = 0
Do while not eof(1)
     count = count + 1
     input #1, mark(count)
Loop
Close #1

 To display all 20 marks in Reverse Order

for x = 20 to 1 step -1
    picOutput.print mark(x)
next x

 To display the values stored in odd elements, backwards, on one line:

For x = 23 to 1 step -2
      picOutput.print (x)
Next x

 To Calculate the total of all ages and the average

total = 0  ' initialize variables
For x = 1 to 24
     total = total + mark(x)
Next x
average = total/24
picOutput.print total, average

To print the highest mark

highest = 0
For x = 1 to 20
    If mark(x) > highest then
         highest = mark(x)
     end if
Next x
picOutput.print highest

Example 1:Reading data into parallel arrays when the number of entries in known.

The table below gives names and test scores from a mathematics contest given in 1953. Write a program to display the names of the students scoring above the average for these eight students.

 Richard Dolen

 133
 Geraldine Ferraro  114
 James B. Fraser  92
 John H. Malby  91
 Paul H. Monsky  130
 Max A. Plager  114
 Rovert A. Shade  91
 Barbara M. White  124

 'The following program creates a string array to hold the names of the contestents
'and a numeric array to hold the scores. The number of contestents is known.

Private Sub cmdShow_Click()
   dim total As Integer
   dim student As Integer
   dim average As Single
 
   'Create arrays for names and scores
 
   dim nom(1 To 8) As String
   dim score(1 To 8) As Integer
 
  'Assume the data has been placed in the file "SCORES.TXT"
  '(The first line of the file is "Richard Dolen",135)
 
   Open App.Path & "\SCORES.TXT" For Input As #1
   For student = 1 To 8
      Input #1, nom(student), score(student)
   Next student
   Close #1

   'Analyze exam scores

   total = 0
   For student = 1 To 8
      total = total + score(student)
   Next student
   average = total / 8

   'Display all names with above average grades
 
   picTopStudents.Cls
   For student = 1 To 8
      If score(student) > average Then
         picTopStudents.Print nom(student)
      End If
   Next student
End Sub

Dynamic arrays

Can be used when you don't know exactly how large to make an array because it can be resized at any time. After a dynamic array is initially declared, you can add new elements as needed, rather than establishing the size of the array at the time the code is written.

You declare the array as dynamic by giving it an empty dimension list as follows:

dim age() as integer

To dimension the array, use the Redim command as follows:

Redim age(1 to 7)

Or, using a variable:

dim count as integer
count = 7
redim age(1 to count)

Note: redim does not specify the type of the array again.

We can even specify both the lower and upper bounds of the array:

dim low as integer
dim upper as integer
Low =2
Upper = 8
Redim age(low to high)

Bounds of the Array

Since the lower and upper bounds can be changed by the redim command, we need a way to find what they have been set at. VB provides 2 functions:

Lbound(arrayname) – returns the value of the lower bound of the array
Ubound(arraynmae) – returns the value of the upper bound of the array

To create a for loop that displays all elements of the array, without knowing the lower or upper bound we can write:

for index = lbound(age) to upper(bound)
  Picoutput.print age(index)
Next index

Arrays as Parameters to functions and subs

Arrays can be sent to functions and subs as parameters. When sending an array as a parameter, just send the array name, not the array size or type.

For example, to send the array age to the lbound() function, we write:

dim age (1 to 8) as integer
dim lower as integer
lower = Lbound(age)

This is true for VB created functions and user-defined functions and subs.

When creating a user-defined sub or function, we specify the array name and type, but not the bounds, in the function header, for example:

private sub displayNames( byref names() as string)

Note: arrays must be passed to subs and functions as byref.

Related Arrays

Two or more arrays are said to be related, if they contain information that goes together, such as one array with student names and a second array with scores. In this case, the index of the arrays ‘connect’ the information in the arrays, for example, index 3 is student name ‘smith’ and index 3 is the score for smith.
'The following program creates a string array to hold the names of the ‘ contestants and a numeric array to hold the scores. The number of contestants ‘ is unknown. Use the data file from the previous question.

private Sub cmdShow_Click()
  dim numStudents As Integer
  dim nTemp As String
  dim sTemp As Integer
  dim student As Integer
  dim Total As Integer
  dim average As Single
  dim nom() as string
  dim score() as integer


  'Determine amount of data to be processed


  numStudents = 0
  Open App.Path & "\SCORES.TXT" For Input As #1
  
  Do While Not EOF(1)
    Input #1, nTemp, sTemp
    numStudents = numStudents + 1
  Loop
  Close #1
  
  'Create arrays for names and scores
  
  redim nom(1 To numStudents) As String
  redim score(1 To numStudents) As Integer
Open App.Path & "\SCORES.TXT" For Input As #1 For student = 1 To numStudents Input #1, nom(student), score(student) Next student Close #1 'Analyze exam scores Total = 0 For student = 1 To numStudents Total = Total + score(student) Next student average = Total / numStudents 'Display all names with above average grades picTopStudents.Cls For student = 1 To numStudents If score(student) > average Then picTopStudents.Print nom(student) End If Next student End Sub

Searching

Linear Search

If we had an array of 500 names and wanted to find the location of a specific name in the array, we could start at the first element of the array, check it, then move to the next element of the array, check it, and so on until we found the name we wanted, or until we reached the end of the array.

The algorithm can be stated as:

current index =  array lower bound

found = false
foundIndex = 0


repeat while not found and current index < array upper bound
  if current list element = desired element then
     found = true
     foundIndex = current index
  else
     add 1 to current index

To code a user-defined function in VB that returned the index of a name in an array of names, we could write:

private function findName(byref names() as string, byval seekName as string) as integer
   dim found as boolean
   dim currentIndex as integer
   dim foundIndex as integer
   
   found = false
   foundIndex = 0
   currentIndex = Lbound(names)
   
   do while (NOT found and currentIndex < Ubound(names))
      if seekName = names(currentIndex) then
	     found = true
		 foundIndex = currentIndex
	  else
	     currentIndex = currentIndex + 1
	  end if
   loop
   
   findName = foundIndex
end sub

The linear search is easy to understand and code. It will work on any array. However, it is not an efficient searching technique.

Binary Search

If we had an array of 500 names in alphabetical order and wanted to locate a specific person in the list we one approach is to start with the first name and consider each name until a match was found. This process is called a linear search. We would find a person’s name that begins with the letter "A" considerably faster than we would a name beginning with "Z". This method is time-consuming for large lists.

If a list has already been sorted a more efficient binary search can be performed.

Sample List:

    1. Alex
    2. Dave
    3. Dan
    4. Dylan
    5. Jason
    6. Kyle
    7. Matt
    8. Saroja

Let’s assume we are looking for the name ‘Kyle’. A binary search looks for which half of the list the name lies in and discards the other half. The retained part of the list now becomes the entire list. This process is repeated until the item is found. A flag can indicate if Kyle is found. This is much the same way you would look up a person in the telephone book.

The algorithm is as follows:

  1. At each stage, denote the subscript of the first item in the retained list by first and the subscript of the last item by last. Initially, the value of first is the lower bound of the array, the value of last is the upper bound of the array, and the value of the found flag is False.
  2. Look at the middle item of the current list, the item having the subscript middle = int(first + last)/2).
  3. If the middle item is Kyle, the flag is set to True and the search is over.
  4. If the middle item is greater than Kyle, then Kyle should be in the first half of the list. So the subscript of Kyle must lie between first and middle – 1. That is, the new value of last is middle – 1
  5. If the middle item is less than Kyle, then Kyle should be in the second half of the list of possible items. So the subscript of Kyle must lie between middle + 1 and last. That is, the new value of first is middle + 1
  6. Repeat steps 2 through 5 until Kyle is found or until the halving process uses up the entire list. (When the entire list has been used up, first >=last.) In the second case, Kyle was not in the original list.

To code a user-defined function in VB that returned the index of a name in an array of names, we could write:

private function findName(byref names() as string, byval seekName as string) as integer
   dim found as boolean
   dim lowIndex as integer
   dim highIndex as integer
   dim middleIndex as integer
   
   found = false
   lowIndex = Lbound(names)
   highIndex = Ubound(names)
   middleIndex = int((highIndex + lowIndex)/2)

   
   do while (NOT found and lowIndex < highIndex)
      if seekName = names(middleIndex) then
	     found = true
	  elseif seekName > names(middleIndex) then
	     lowIndex = middleIndex + 1
        middleIndex = int((highIndex + lowIndex)/2)
     else
        highIndex = middleIndex - 1
        middleIndex = int((highIndex + lowIndex)/2)
	  end if
   loop
   
	if found = true then
      findName = middleIndex
   else
      findName = -1
   end if

end sub

The binary search is not as easy to code or understand as the linear search, and the array must be sorted, however, it is much more efficient than the linear searching technique.

Sort Algorithms

There are many different types of sorting routines. Here are some examples. Below is the pseudocode for two different sorts.

Selection Sort

In a selection sort, we start at one end of the array looking for the largest or smallest depending on whether the sort is in ascending or descending order. Once found, we can place it in it's proper spot and continue searching through the remaining elements in the array. Once an element has been swapped, it is never moved again. One disadvantage to this type of sort is that it must perform N2 passes through the array regardless of the original order.

for i = the beginning of the array to the end 

look for the smallest (or largest) element and put it in the ith element for j = the ith element to the last element if the jth element is smaller than the ith element swap the jth element with the ith element

More information is here.

Bubble Sort

In a bubble sort, adjacent values are compared and exchanged if they are not in order. It uses a boolean variable "SORTED" which determines if the list is sorted and stops execution if found to be in order. Although many more swaps are performed in this sort, it is especially efficient if only a few elements have been added to the array, since the sort is a "smart" sort and stops when the boolean flag becomes true.

procedure sort 
   set sorted to false 
   set max to top 
   while not sorted and top > 1 
      set sorted to true 
      for passes = 1 to top -1 
         if element at i > list at i + 1 
         exchange the i th element with the i th + 1 element 
         set top to top -1

More information is found here, and also here. A quiz if found here.

Multidimensional Arrays:

Two dimensional arrays can be thought of as looking like a table, with rows and columns. The rows are the first dimension and the columns are the second dimension.

   
columns
|
v
   
 
       
       
       
       
rows ->
 
 

 

The following statement declares a two-dimensional 10-by-10 array:

dim matrixA(1 to 10, 1 to 10) as single

Two dimensional arrays can also be dynamic arrays and declared without any size and then later dimensioned, for example:

dim matrixA() as single
dim matrixA(1 to 5, 1 to 7)

To determine the number of rows and columns of an existing two dimensional array, we can use the UBound command. The parameter after the array name is the dimension number we are interested in getting. For example:

dim rows as integer
dim columns as integer
rows = UBound(matrixA, 1)
columns = UBound(matrixA, 2)

When accessing an element of a two dimensional array, we must always specify both dimensions. For example, the output the value of an element in row 5, column 2 to a picture box, we would write:

picOutput.print matrixA(5, 2)

Two dimensional arrays are often processed in nested for loops. For example, to output all elements of a matrix to a picture box, we would write:

for row = LBound(matrixA, 1) to UBound(matrixA, 1)
   for column = LBound(matrixA, 2) to UBound(matrixA, 2)
      picOutput.print matrixA(row, column)
   next column
next row

Menus

You can make your VB projects very professional by adding menus to your programs. In order to create menus you need to run the menu editor. You select menu editor from the tools menu, press CTRL + E or click on the menu editor icon on the toolbar.

ALT + letter shortcuts:

Type an & in front of the letter for which you would like the shortcut. For example, if you want ALT + f in the file menu simply type &File in the caption section of the menu editor

Submenu items:

There are built in shortcut options for your submenu items in the menu editor window.

Code:

To add code to the menu option simply click on the menu item in the project window and you will revert to the code window with the sub/end sub for that menu item. Add you code.

Timer Objects

A timer can be placed on a form. It does not appear when the program is run. The timer goes off after a set number of clicks (interval property). When the timer goes off it runs the code in the timer_timer sub. It continues to run the program in the timer sub every time the time interval is reached and in that sense is also a repetition structure.

 

Moving Images

Images have 2 properties that control where the image appears on the form - .left and .top. The numbers for these properties start at the upper left corner of the form. As the top number increases the image moves down the screen. As the left number increases the images moves to the right

Move Command:

To move the image use the move command:

image.move image.left +/- number, image.top +/- numberSwitching images (to give the illusion of animation)

You can change the picture shown by an image by copying the picture from another image object (usually invisible).

image1.picture = image2.picture

changes image1

The switching is done by a boolean variable, if statement and a not.

Example of switching images:

in module

public switch as boolean

in timer

if switch then
    realimage.picture = invisibleimage1.picture
else
    realimage.picture = invisibleimage2.picture
end if
switch = not switch