0% found this document useful (0 votes)
14 views31 pages

COS 102 Introduction To PS Part 2

Uploaded by

mozeez0943
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views31 pages

COS 102 Introduction To PS Part 2

Uploaded by

mozeez0943
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

LECTURE 6: IMPLEMENTATION OF ALGORITHM IN PROGRAMMING

LANGUAGE: VISUAL BASIC (VB) PROGRAMMING


6.1 Introduction
Programming involves creating series of instructions aimed at directing a computer to perform
tasks far more efficiently than humans. The initial programming language, known as machine
language, relied on binary code (0s & 1s) to establish communication with the computer.
Machine language posed significant challenges due to its complexity. Thankfully, scientists
have since developed high-level programming languages that are considerably more user-
friendly and accessible for mastering. Among the high-level programming languages are
Java, Javascript, C, C++, c# and Visual Basic.
Visual Basic (VB) is a programming language and integrated development environment
(IDE) that provides a foundation for building applications and programs within Windows-
based operating systems. VB is an event-driven, object-oriented programming language and a
programming environment. It offers a graphical user interface (GUI) for an easy
user experience, with menus, text boxes, buttons, checkboxes, and other intuitive elements. VB
allows users to manipulate GUI elements by dragging and dropping objects to the interface and
then defining their appearance and behaviour. The language is a derivative of the Beginners'
All-purpose Symbolic Instruction Code (BASIC) programming language1.
6.2 Objectives
At the end of the lecture, students should understand.
• Concept of VB
• VB integrated Development Environment
• Building VB Application
• Working with controls
• Writing the Code
• Managing VB Data
• Managing Variables
• Decision tree and table

6.3 Concept of VB

Visual Basic is a third-generation event-driven programming language first released by


Microsoft in 1991. It evolved from the earlier DOS version called
BASIC. BASIC means Beginners' All-purpose Symbolic Instruction Code. Since then,
Microsoft has released many versions of Visual Basic, from Visual Basic 1.0 to the final
version Visual Basic 6.0. Visual Basic is a user-friendly programming language designed for
beginners, and it enables anyone to develop GUI window applications easily.

1 https://www.indeed.com/career-advice/career-development/how-to-learn-visual-basic
In 2002, Microsoft released Visual Basic.NET (VB.NET) to replace Visual Basic 6. Thereafter,
Microsoft declared VB6 a legacy programming language in 2008. Fortunately, Microsoft still
provides some form of support for VB6. VB.NET is a fully object-oriented programming
language implemented in the .NET Framework. It was created to cater for the development of
the web as well as mobile applications.

6.4 VB 6 Integrated Development Environment (IDE)


VB 6 compiler needs to be installed in any computer system before VB programs could be
written. User can purchase this software copy: Microsoft Visual Basic 6.0 Learning Edition
or Microsoft Visual Basic Professional Edition from Amazon.com, both are vb6 compilers.
These can be purchased from eBay at Microsoft Visual Basic 6.0 6 Professional PRO MSDN
Library Manual Service Pack. Additionally, with installed Microsoft Office in a PC or laptop,
one can use the built-in Visual Basic Application in Excel to start creating Visual Basic
programs without having to spend extra cash to buy the VB6 compiler. One can also download
and install VB6 from Microsoft.com on Windows 10 but need to follow certain steps otherwise
the installation will fail.
After installing the vb6 compiler, the icon will appear on desktop or in programs menu. Click
on the icon to launch the VB6 compiler. On start up, Visual Basic 6.0 will display the following
dialog box as shown in Figure 6.1.

Figure 6.1: New Project Dialog

Options: choose to either start a new project, open an existing project, or select a list of recently
opened programs. A project is a collection of files that make up an application. There are
various types of applications that one could create, however, concentration is on creating
Standard EXE programs (EXE means executable). Next, click on the Standard EXE icon to go
into the actual Visual Basic 6 programming environment.
A new VB 6 Standard EXE project IDE is shown in figure 6.2. It consists of the toolbox, the
form, the project explorer, and the properties window.

Figure 6.2: VB6 Programming Environment

The Form is the primary building block of a VB 6 application. Before proceeding to building
an application, it is a good practice to save the project first. Save the project by
selecting Save Project from the File menu, assign a name to your project and save it in a certain
folder.

6.5 Building VB Applications


6.5.1 Creating VB Application
Launch Microsoft VB 6 compiler. In the New Project Dialog, choose Standard EXE to enter
Visual Basic 6 IDE. In the VB6 IDE, a default form with the name Form1 will appear. Next,
double click on Form1 to bring up the source code window for Form1, as shown in Figure 6.3.
The top of the source code window consists of a list of objects and their associated events or
procedures. In the source code window, the object displayed is Form1 and the associated
procedure is Load.
Figure 6.3: The VB6 Source Code Window
When object box is clicked, drop-down list will display a list of objects inserted into form, as
shown in figure 6.4. Here, there are a form with the name Form1, a command button with the
name Command1, a Label with the name Label1 and a Picture Box with the name Picture1.

Figure 6.4: List of Objects


Similarly, click on the procedure box, a list of procedures associated with the object will be
displayed, as shown in Figure 6.5. Some of the procedures associated with the object Form1
are Activate, Click, DblClick (which means Double-Click), DragDrop, keyPress and more.
Each object has its own set of procedures. One can always select an object and write codes for
any of its procedure to perform certain tasks.
Figure 6.5: List of Procedures

Note about the beginning and the end statements (i.e. Private Sub Form_Load.......End Sub.);
Just key in the lines in between the above two statements exactly as are shown here. When
F5 is pressed to run the program, nothing showed up. In order to display the output of the
program, one needs to add the Form1.show statement like in Example or just
use Form_Activate ( ) event procedure as shown in example 2. The command Print does not
mean printing using a printer, but it means displaying the output on the computer screen. Now,
press F5 or click on the run button to run the program with the output as shown in Figure 6.6
Also perform arithmetic calculations as shown in Example 2. VB uses * to denote the
multiplication operator and / to denote the division operator. The output is shown in Figure 6.7,
where the results are arranged vertically.
Example 1
Private Sub Form_Load ( )
Form1.show
Print "Welcome to Visual Basic tutorial"
End Sub
Example 2
Private Sub Form_Activate ( )
Print 20 + 10
Print 20 - 10
Print 20 * 10
Print 20 / 10
End Sub
Figure 6.6: The output of Example 1

Figure 6.7: The output of Example 2


Use the + or the & operator to join two or more texts (string) together like in example 3 (a), (b)
Example 3 (a)
Private Sub
A = "Tom"
B = "likes"
C = "to"
D = "eat"
E = "burger"
Print A + B + C + D + E
End Sub
Example 3 (b)
Private Sub
A = "Tom"
B = "likes"
C = "to"
D = "eat"
E = "burger"
Print A & B & C & D & E
End Sub
The Output of Example 3 (a) &(b) is as shown in Figure 6.8.

Figure 6.8

6.5.2 Steps in Building a Visual Basic Application


Step 1: Design the interface by adding controls to the form and set their properties.
Step 2: Write code for the event procedures.
Example: Changing Background and Foreground Colour at Random
This example shows how to write code to change the background and the foreground colour
randomly. Add two command buttons and a label on the form. One of the command buttons
will be used to change the background colour while the other one will be used to change the
foreground colour. The Label is for displaying the foreground colour. There are two events
here, change background colour and change foreground colour. There is need to write code
for the two event procedures.
To make the program more interesting, the Rnd() function, the Int() function and the RGB
codes are used to change the colour randomly. The Rnd() function creates a random number
between 0 and 1 and the RGB code uses a combination of three integers to form a certain
colour. The Int() is a function that converts a number into an integer by truncating its decimal
part and the resulting integer is the largest integer that is smaller than the number. For example,
Int(0.2)=0, Int(2.4)=2, Int(4.8)=4. Therefore, Int(Rnd()*256) returns the smallest integer 0 and
the biggest integer 255. The format of RGB code is RGB(a,b,c), where a, b, c range from 0 to
255. For example, RGB(255,0,0) is red, RGB(255,255,255) is white and (0,0,0) is black.
Now, rename the controls as follows:
Form1-MyForm
Label1-LblMessage
Command1-cmd_bgColor
Command2-cmd_fgColor
Next, change the caption of the Label to "Please Change My Colour". In addition, change the
caption of Command1 button to "Change Background Colour" and change the caption of
Command2 button to "Change Foreground Colour”.
Now, enter the following code.
Private Sub cmd_bgColor_Click()
Dim r, g, b As Integer
r = Int(Rnd() * 256)
g = Int(Rnd() * 256)
b = Int(Rnd() * 256)
MyForm.BackColor = RGB(r, g, b)
End Sub
Private Sub Cmd_fgColor_Click()
Dim r, g, b As Integer
r = Int(Rnd() * 256)
g = Int(Rnd() * 256)
b = Int(Rnd() * 256)
Lbl_Msg.ForeColor = RGB(r, g, b)
End Sub
Run the program, each time by press on the 'Change Background Colour' button, different
background colour would be shown. Similarly, each time 'Change Foreground Colour', is
pressed, message on the Label changes colour would be shown. The output is shown in Figure
6.9

Figure 6.9
6.6. Working With Controls
6.6.1 The Control Properties
To effectively write an event procedure for a control to respond to an event, it is necessary to
configure specific properties that dictate its appearance and functionality. These properties can
be set either through the properties window or dynamically during runtime.
Figure 6.10 is a typical properties window for a form. In the properties window, the item
appears at the top part is the object currently selected. At the bottom part, the items listed in the
left column represent the names of various properties associated with the selected object while
the items listed in the right column represent the states of the properties. Properties can be set
by highlighting the items in the right column then change them by typing or selecting the
options available.

Figure 6.10. Properties Window


For example, to change the caption, just highlight Form1 under the name Caption and change
it to other names. The appearance of the form can be altered by setting it to 3D or flat, change
its foreground and background colour, change the font type and font size, enable, or disable,
minimize, and maximize buttons and more.
The properties can also be changed at runtime to give special effects such as change of colour,
shape, animation effect and so on. As shown in example, the code that will change the form
colour to red every time the form is loaded. VB uses the hexadecimal system to represent the
colour. The colour codes can be checked in the properties windows which are showing up under
ForeColour and BackColour.
Example: Program to change background colour
This example changes the background colour of the form using the BackColour property.
Private Sub Form_Load()
Form1.Show
Form1.BackColor = &H000000FF&
End Sub
Example: Program to change shape
This example is to change the control's Shape using the Shape property. This code will change
the shape to a circle at runtime.
Private Sub Form_Load()
Shape1.Shape = 3
End Sub
6.6.2 Handling some of the common Controls
Figure 6.11 below is the VB6 toolbox that shows the basic controls.

Figure 6.11: Toolbox


The Text Box: The text box is the standard control for accepting input from the user as well as
to display the output. It can handle string (text) and numeric data but not images or pictures. A
string entered into a text box can be converted to a numeric data by using the function Val(text).
The following example illustrates a simple program that processes the input from the user.
Example
In this program, two text boxes are inserted into the form together with a few labels. The two
text boxes are used to accept inputs from the user and one of the labels will be used to display
the sum of two numbers that are entered into the two text boxes. Besides, a command button is
also programmed to calculate the sum of the two numbers using the plus operator. The program
use creates a variable sum to accept the summation of values from text box 1 and text box 2.
The procedure to calculate and to display the output on the label is shown below.
Private Sub Command1_Click()
'To add the values in TextBox1 and TextBox2
Sum = Val(Text1.Text) +Val(Text2.Text)
'To display the answer on label 1
Label1.Caption = Sum
End Sub
The output is shown in Figure 6.12

Figure 6.12: The output


The Label: The label is a very useful control for Visual Basic, as it is not only used to provide
instructions and guides to the users, but it can also be used to display outputs. One of its most
important properties is Caption. Using the syntax Label.Caption, it can display text and
numeric data. You can change its caption in the properties window and also at runtime. Please
refer to example above and Figure 6.12 for the usage of the label.
The Command Button: The command button is one of the most important controls as it is
used to execute commands. It displays an illusion that the button is pressed when the user clicks
on it. The most common event associated with the command button is the Click event, and the
syntax for the procedure is:
Private Sub Command1_Click ()
Statements
End Sub
The Picture Box: The Picture Box is one of the controls that is used to handle graphics. You
can load a picture at design phase by clicking on the picture item in the properties window and
select the picture from the selected folder. You can also load the picture at runtime using
the LoadPicture method. For example, the statement will load the picture grape.gif into the
picture box.
Picture1.Picture=LoadPicture ("C:\VBprogram\Images\grape.gif")
Example Loading Picture
In this program, insert a command button and a picture box. Enter the following code:
Private Sub cmd_LoadPic_Click()
MyPicture.Picture = LoadPicture("add path to access the picture")
End Sub
* The path to access the picture must be entered and should be correct for picture to be
uploaded. Besides that, the image in the picture box is not resizable. The output is shown in
Figure 6.13

Figure 6.13: The Picture Viewer


The List Box: The function of the List Box is to present a list of items where the user can click
and select the items from the list. In order to add items to the list, the AddItem method can be
used. For example, to add a number of items to list box 1, the following statements can be used.
Example
Private Sub Form_Load( )
List1.AddItem “Lesson1”
List1.AddItem “Lesson2”
List1.AddItem “Lesson3”
List1.AddItem “Lesson4”
End Sub
The Output
Figure 6.14: The List Box
The Combo Box: The function of the Combo Box is also to present a list of items where the
user can click and select the items from the list. However, the user needs to click on the small
arrowhead on the right of the combo box to see the items which are presented in a drop-down
list. To add items to the list, use the AddItem method. For example, to add a number of items
to Combo box 1, the following statements suffice.
Example
Private Sub Form_Load( )
Combo1.AddItem "Item1"
Combo1.AddItem "Item2"
Combo1.AddItem "Item3"
Combo1.AddItem "Item4"
End Sub
The Output

Figure 6.15: List Box


The Check Box: The Check Box control lets the user selects or unselects an option. When the
Check Box is checked, its value is set to 1 and when it is unchecked, the value is set to 0. The
statements Check1.Value=1can be included to mark the Check Box and Check1.Value=0 to
unmark the Check Box, as well as use them to initiate certain actions. For example
Private Sub Cmd_OK_Click()
If Check1.Value = 1 And Check2.Value = 0 And Check3.Value = 0 Then
MsgBox "Apple is selected"
ElseIf Check2.Value = 1 And Check1.Value = 0 And Check3.Value = 0 Then
MsgBox "Orange is selected"
ElseIf Check3.Value = 1 And Check1.Value = 0 And Check2.Value = 0 Then
MsgBox "Orange is selected"
ElseIf Check2.Value = 1 And Check1.Value = 1 And Check3.Value = 0 Then
MsgBox "Apple and Orange are selected"
ElseIf Check3.Value = 1 And Check1.Value = 1 And Check2.Value = 0 Then
MsgBox "Apple and Pear are selected"
ElseIf Check2.Value = 1 And Check3.Value = 1 And Check1.Value = 0 Then
MsgBox "Orange and Pear are selected"
Else
MsgBox "All are selected"
End If
End Sub
The Output

Figure 6.16: The List Box


6.7 Writing the Code
Essential techniques for writing Visual Basic program code are illustrated here. It is crucial to
understand that each control or object in VB has the potential to initiate various events. These
events are neatly catalogued in the dropdown menu within the code window. To unlock this
menu, just double-click on an object and pick your preferred event from the procedures' box.
The array of events covers form loading, command button clicks, keyboard key presses, object
dragging, and more.
To start writing code for an event procedure, double-click an object to enter the VB code
window. For example, to write code for the event of clicking a command button, double-click
the command button and enter the codes in the event procedure that appears in the code
window, as shown in Figure 6.17

Figure 6.17
The structure of an event procedure is as follows:
Private Sub Command1_Click
VB Statements
End Sub
Enter the codes in the space between Private Sub Command1_Click............. End Sub. The
keyword Sub stands for a sub procedure that made up a part of all the procedures in a program
or a module. The program code is made up of several VB statements that set certain properties
or trigger some actions. The syntax of the Visual Basic’s program code is almost like the
normal English language, though not the same, so it is easy to learn.
The syntax to set the property of an object or to pass a certain value to it is:
Object.Property
where Object and Property are separated by a period (or dot). For example, the
statement Form1.Show means to show the form with the name
Form1, Iabel1.Visible=true means label1 is set to be visible, Text1.text=”VB” is to assign
the text VB to the text box with the name Text1, Text2.text=100 is to pass a value of 100 to
the text box with the name text2, Timer1.Enabled=False is to disable the timer with the name
Timer1 and so on. Let’s examine a few examples below:
Example 1
Private Sub Command1_click()
Label1.Visible=false
Label2.Visible=True
Text1.Text="You are correct!"
End sub
Example 2
Private Sub Command1_click()
Label1.Caption="Welcome"
Image1.visible=true
End sub

6.8 Managing VB Data


Visual Basic Data Types
Data come in different aspects-names, addresses, monetary values, dates, stock quotes, and
statistics-all constituting a diverse array of information. Similarly, when immersed in the realm
of Visual Basic, there are several data forms, ranging from mathematically calculable values to
various textual and other formats. To streamline the coding process for optimal efficiency, VB
neatly organizes data into distinct categories. In the case of VB6, these categories
predominantly manifest as numeric data types and non-numeric data types.
6.8.1 Numeric Data Types
Numeric data types are fundamental data types that encompass numbers capable of being
manipulated through mathematical computations using standard operators. They serve as
containers for various types of quantitative information, such as height, weight, share values,
prices of goods, monthly bills, fees, and more. In Visual Basic, numeric data is categorized into
seven distinct types based on the range of values they can accommodate.
Calculations involving round figures can make use of the Integer or Long Integer data types.
However, for programs that necessitate high precision calculations, the preferred choice is to
employ the Single and Double data types, commonly known as floating-point numbers. When
it comes to currency calculations, it is advisable to use currency data types. Lastly, if utmost
precision is indispensable for calculations involving numerous decimal points, the decimal data
types prove to be the most suitable option. These data types summarized in Table 6.1.
Table 6.1: Numeric Data Types

Type Storage Range of Values

Byte 1 byte 0 to 255

Integer 2 bytes -32,768 to 32,767

Long 4 bytes -2,147,483,648 to 2,147,483,648

-3.402823E+38 to -1.401298E-45 for negative values 1.401298E-45 to


Single 4 bytes
3.402823E+38 for positive values.

-1.79769313486232e+308 to -4.94065645841247E-324 for negative


Double 8 bytes values 4.94065645841247E-324 to 1.79769313486232e+308 for
positive values.

Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807

+/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use +/-


Decimal 12 bytes
7.9228162514264337593543950335 (28 decimal places).

6.8.2 Non-numeric Data Types


Non-numeric data types are data that cannot be manipulated mathematically. Non-numeric data
comprises string data types, date data types, Boolean data types that store only two values (true
or false), object data type and Variant data type. They are summarized in Table 6.2.

Table 6.2: Nonnumeric Data Types

Data Type Storage Range

String(fixed length) Length of string 1 to 65,400 characters

String(variable length) Length + 10 bytes 0 to 2 billion characters

Date 8 bytes January 1, 100 to December 31, 9999

Boolean 2 bytes True or False

Object 4 bytes Any embedded object

Variant(numeric) 16 bytes Any value as large as Double


Variant(text) Length+22 bytes Same as variable-length string

Suffixes for Literals: Literals are values that are assigned to data. In some cases, there is need
to add a suffix behind a literal so that VB can handle the calculation more accurately. For
example, use num=1.3089# for a Double type data. Some of the suffixes are displayed in Table
6.3.

Table 6.3: Suffixes for Literals

Suffix Data Type

& Long

! Single

# Double

@ Currency

In addition, we need to enclose string literals within two quotations and date and time literals
within two # sign. Strings can contain any characters, including numbers. The following are
few examples:
memberName="Turban,John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#
6.9 Managing Variables
Variables are like mailboxes in the post office. The contents of the variables change every now
and then, just like the mailboxes. In term of VB, variables are areas allocated by the computer
memory to hold data. Like the mailboxes, each variable must be given a name. To name a
variable in Visual Basic, there are a set of rules to follow.
6.9.1 Variable Names
The following are the rules when naming the variables in Visual Basic
i. It must be less than 255 characters.
ii. No spacing is allowed.
iii. It must not begin with a number.
iv. Period is not permitted.
v. Cannot use exclamation mark (!), or the characters @, &, $, #.
vi. Cannot repeat names within the same level of scope.
Examples of valid and invalid variable names are displayed in Table 6.4

Table 6.4: Examples of Valid and Invalid Variable Names

Valid Name Invalid Name

My_Car My.Car

this year 1NewBoy

Long_Name_Can_beUSE He&HisFather *& is not acceptable

6.9.2 Declaring Variables Explicitly


In Visual Basic, it is a good practice to declare the variables before using them by assigning
names and data types. They are normally declared in the general section of the codes' windows
using the Dim statement. The syntax is as follows:
Dim VariableName As DataType
Variables can be declared in separate lines or combined more in one line, separating each
variable with a comma, as follows:
Dim VariableName1 As DataType1, VariableName2 As DataType2,
VariableName3 As DataType3
Example
Dim password As String
Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim doDate As Date
Dim password As String, yourName As String, firstnum As Integer
Unlike other programming languages, Visual Basic does not require one to specifically declare
a variable before it is used. If a variable is not declared, VB will automatically declare the
variable as a Variant. A variant is data type that can hold any type of data.
For string declaration, there are two possible types, one for the variable-length string and
another for the fixed-length string. For the variable-length string, use the same format as
example above. However, for the fixed-length string, the syntax shown below is used:
Dim VariableName as String * n
where n defines the number of characters the string can hold.
For example,
Dim yourName as String * 10
*yourName can holds no more than 10 Characters.
6.9.3 Scope of Declaration
Other than using the Dim keyword to declare the data, other keywords can be used to declare
the data. Three other keywords are private, static, and public. The forms are as shown below:
Private VariableName as Datatype
Static VariableName as Datatype
Public VariableName as Datatype
The above keywords indicate the scope of the declaration. Private declares a local variable or
a variable that is local to a procedure or module. However, Private is rarely used, normally use
Dim to declare a local variable.
The Static keyword declares a variable that is being used multiple times, even after a procedure
has been terminated. Most variables created inside a procedure are discarded by Visual Basic
when the procedure is finished, static keyword preserves the value of a variable even after the
procedure is terminated.
Public is the keyword that declares a global variable, which means it can be used by all the
procedures and modules of the whole program.
6.9.4 Constants
Constants are different from variables in the sense that their values do not change during the
running of the program.
Declaring a Constant
The syntax to declare a constant is:
Constant Name As Data Type = Value
Example
In this example, four variables and a constant are declared. The variable h is to store the value
of height of the circle and the variable r is to store the value of the radius which is half of the
height. In addition, the variable a is to store the value of area in twip using the formula area of
circle=πr2. Besides that, the constant Pi represents π which is fixed at 3.142. Finally, the
variable area is to store the value in cm by multiplying a with 0.001763889. (1 twip
=0.001763889 cm)
The Code
Dim h, r, a, rad, area As Single
Const Pi As Single = 3.142
Private Sub CmdArea_Click()
r=h/2
rad = r * 0.001763889
a = Pi * rad ^ 2
area = Round(a, 2)
MsgBox ("The Area of the circle is " & area)
End

6.9.5 Working with Variables


Assigning Values to Variables
After declaring various variables using the Dim statements, one can assign values to those
variables. The syntax of an assignment is:
Variable=Expression
The variable can be a declared variable or a control property value. The expression could be a
mathematical expression, a number, a string, a Boolean value (true or false) and more.
The following are some examples variable assignment:
firstNumber=100
secondNumber=firstNumber-99
userName="John Lyan"
userpass.Text = password
Label1.Visible = True
Command1.Visible = false
Label4.Caption = textbox1.Text
ThirdNumber = Val(usernum1.Text)
X = (3.14159 / 180) * A

6.10 Operators in Visual Basic


To compute inputs from users and to generate results, various mathematical operators are
needed. In Visual Basic mathematical operators are shown in Table 6.5.
Table 6.5: Arithmetic Operators

Operator Mathematical function Example>

^ Exponential 2^4=16

* Multiplication 4*3=12,

/ Division 12/4=3

Modulus (returns the remainder from an integer


Mod 15 Mod 4=3
division)

\ Integer Division (discards the decimal places) 19\4=4

"Visual"&"Basic"="Visual
+ or & String concatenation
Basic"

Example 1
Private Sub Command1_Click()
Dim firstName As String
Dim secondName As String
Dim yourName As String

firstName = Text1.Text
secondName = Text2.Text
yourName = secondName +"" + firstName
Label1.Caption = yourName
End Sub
In this example, three variables are declared as string. For variables firstName and secondName
will receive their data from the user’s input into textbox1 and textbox2, and the variable
yourName will be assigned the data by combining the first two variables. Finally, yourName
is displayed on Label1.
Example 2
Dim number1, number2, number3 as Integer
Dim total, average as variant
Private sub Form_Click()

number1=val(Text1.Text)
number2=val(Text2.Text)
number3= val(Text3.Text)
Total=number1+number2+number3
Average=Total/5
Label1.Caption=Total
Label2.Caption=Average
End Sub
In the Example 2, three variables are declared as integer and two variables are declared as
variant. Variant means the variable can hold any data type. The program computes the total and
average of the three numbers that are entered into three text boxes.
6.11 If statement
This concerns decision-making in VB code, where one processes user input and direct the
program flow accordingly. The ability to make decisions is a crucial aspect of programming,
enabling intelligent problem-solving and generating meaningful output or feedback for the
user. For instance, one can construct a program that prompts the computer to execute specific
tasks until a predefined condition is satisfied.
6.11.1 Conditional Operators
To control the VB program flow, one can use various conditional operators. Basically, they
resemble mathematical operators. Conditional operators are very powerful tools, they let the
VB program compare data values and then decide what action to take, whether to execute a
program or terminate the program and more. These operators are shown in Table 6.6.
Table 6.6: Conditional Operators

Operator Meaning

= Equal to

> More than

< Less Than


> More than or equal

<= Less than or equal

<> Not Equal to

6.11.2 Logical Operators


In addition to conditional operators, there are a few logical operators that offer added power to
the VB programs. They are shown in Table 6.7.
Table 6.7: Logical Operators

Operator Description

And Both sides must be true

Or One side or other must be true

Xor One side or other must be true but not both

Not Negates true

Using If.....Then.....Else Statements with Operators


To effectively control the VB program flow, use If...Then...Else statement together with the
conditional operators and logical operators.
If conditions Then
VB expressions
Else
VB expressions
End If
Example
This example calculates the commission based on sales volume attained. Let's say the
commission structure is laid out as in the table below:

Sale Volume ($) Commission (%)

<5000 0

5000-9999 5
1000-14999 10

15000-19999 15

20000 and above 20

In this example, we insert a textbox to accept sale volume input and a label to display
commission. Insert a command button to trigger the calculation.
The Code

Private Sub cmdCalComm_Click()


Dim salevol, comm As Currency
salevol = Val(TxtSaleVol.Text)
If salevol >= 5000 And salevol < 10000 Then
comm = salevol * 0.05
ElseIf salevol >= 10000 And salevol < 15000 Then
comm = salevol * 0.1
ElseIf salevol >= 15000 And salevol < 20000 Then
comm = salevol * 0.15
ElseIf salevol >= 20000 Then
comm = salevol * 0.2
Else
comm = 0
End If
LblComm.Caption = Format(comm, "$#,##0.00")
End Sub
The Output
Figure 6.18

6.12 More Problem-solving tools


6.12.1 Decision Tree
A Decision Tree is a graph that uses a branching method to display all the possible outcomes
of any decision. In order ways, decision tree is a decision support hierarchical model that uses
a tree-like model of decisions and their possible consequences, including chance event
outcomes and resource costs. It is one way to display an algorithm that only contains
conditional control statements.
Decision tree helps in processing logic involved in decision-making, and corresponding actions
that are taken. It is a diagram that shows conditions and their alternative actions within a
horizontal tree framework. It helps the analyst consider the sequence of decisions and identifies
the accurate decision that must be made. Decision trees are commonly used in operations
research, specifically in decision analysis, to help identify a strategy most likely to reach a goal,
but are also a popular tool in machine learning.
Generally, A decision tree is a flowchart-like structure in which each internal node represents
a "test" on an attribute (e.g. whether a coin flip comes up heads or tails), each branch represents
the outcome of the test, and each leaf node represents a class label (decision taken after
computing all attributes). The paths from root to leaf represent classification rules.
Example of constructing decision tree.
Conditions included the sale amount (under $50) and whether the customer paid by cheque or
with credit card. The four steps possible were to:
i. Complete the sale after verifying the signature.
ii. Complete the sale with no signature needed.
iii. Communicate electronically with the bank for credit card authorization.
iv. Call the supervisor for approval.
The below figure illustrates how this example can be drawn as a decision tree.

Figure 6.19: Decision tree2


Advantages of decision trees
i. Decision trees represent the logic of If-Else in a pictorial form.
ii. Decision trees help the analyst to identify the actual decision to be made.
iii. Decision trees are useful for expressing the logic when the value is variable or action
depending on a nested decision.
iv. It is used to verify the problems that involve a limited number of actions.

6.12.2 Decision Table


Decision tables are a concise visual representation for specifying which actions to perform
depending on given conditions. They are algorithms whose output is a set of actions. The
information expressed in decision tables could also be represented as decision trees or in
a programming language as a series of if-then-else and switch-case statements.
Each decision corresponds to a variable, relation or predicate whose possible values are listed
among the condition alternatives. Each action is a procedure or operation to perform, and the
entries specify whether (or in what order) the action is to be performed for the set of condition
alternatives the entry corresponds to.
Example of Decision Table
Let us consider the decision table given in table 6.8.

2 https://www.codingninjas.com/studio/library/decision-tree-and-decision-table
In the table, there are multiple rules for a single decision. The rules from a decision table can
be made by just putting AND between conditions.
The major rules which can be extracted (taken out) from the table are:
• R1 = If (working day = Y) ^ (holiday = N) ^ (Rainy-day = Y) Then, Go to office.
• R2 = If (working day = N) ^ (holiday = N) ^ (Rainy-day = N) Then, Go to office.
• R3 = If (working day = N) ^ (holiday = Y) ^ (Rainy-day = Y) Then, Watch TV.
• R4 = If (working day = N) ^ (holiday = Y) ^ (Rainy-day = N) Then, Go to picnic.
Table 6.8
1 2 3 4
Working day Y N N N
Holiday N N Y Y
Rainy day Y N Y N
Go to office Y Y
Go to picnic Y
Watch TV Y

Using this table, same information can be transformed to decision tree.


The following rules are constructed from the decision tree.
R1= If (Day = Working) ^ (Outlook = Rainy)
Then Go To Office

R2= If (Day = Working) ^ (Outlook = Sunny)


Then Go To Office

R3= If (Day = Holiday) ^ (Outlook = Rainy)


Then Watch TV

R4=If (Day = Holiday) ^ (Outlook = Sunny)


Then Go To Picnic
Figure 6.20: Decision tree from decision table3.
Stepwise Refinement: Stepwise Refinement is the process of breaking down a programming
problem into a series of steps. It represents a general set of steps to solve a problem, defining
each in turn. Once each step is defined, the problem is broken down into a series of smaller
sub-steps. The idea is to continue until the problem is described in such level of detail that one
can code a solution to the problem.
Stepwise refinement can be represented diagrammatically as:

Figure 6.21: Stepwise refinement.

Evaluation
The final step of the problem-solving cycle is evaluation and learning. Evaluation refers to the
careful observation and assessment of the process and the effects. An evaluation should tell
whether a project is successfully completed, whether improvements need to be implemented
and what can be learnt for the future.

3
https://www.codingninjas.com/studio/library/decision-tree-and-decision-table
Evaluations can be performed with four objectives in mind. First, evaluations serve the current
problem-solving project by determining the results achieved and the improvements to be made.
This is evaluation in a strict sense. In a broader sense, for which the term ‘learning’ is used,
evaluation serves three further objectives. As a second objective, evaluation may also be
oriented towards learning for future problems in the same context. This use of evaluation and
learning is particularly stressed in the literature on organizational learning and knowledge
management. Third, evaluation and learning can be oriented towards advancing generic
scientific knowledge about this type of business process. Finally, evaluation and learning are
necessary for personal and professional learning and development.
Reference
1. https://www.vbtutor.net/lesson8.html
2. https://www.indeed.com/career-advice/career-development/how-to-learn-visual-basic
3. https://www.codingninjas.com/studio/library/decision-tree-and-decision-table
4. https://learnlearn.uk/alevelcs/stepwise-
refinement/#:~:text=Stepwise%20Refinement%20is%20the%20process,series%20of%20smal
ler%20sub%2Dsteps.
5. https://en.wikipedia.org/wiki/Decision_tree
6. https://www.codingninjas.com/studio/library/decision-tree-and-decision-table

You might also like