6 Programming Fundamentals(1)-1
6 Programming Fundamentals(1)-1
Objectives
Contents
• definitions (computer program, programming, compiler, translator,
assembler)
• history of programming languages (machine language, assembly
language, high level languages)
• programming languages (examples: pascal, fortran, COBOL, C, C++,
Java, HTML, visual basic)
• programming techniques
o constructing a computer programme
▪ programme-structure
▪ compiling a computer programme
▪ running a computer programme
o program constructs
▪ discussing data types
▪ discussing data variables
▪ modifying data variables
▪ discussing how to access data types
▪ key words (calculate, count)
▪ input and output (read, display, print)
• designing programs that Read from the keyboard
using the Read command
• writing to the terminal using the Write command
▪ Operators (arithmetic: addition, subtraction, multiplication,
division, logical: and, or, not comparison operators; equal
to, not equal to, less than, greater than)
• using arithmetic operators: + (plus), - (minus), //
(forward slash, * (multiplication)
1
• using Boolean and comparison operators in
programming (arithmetic: Addition, Subtraction,
Multiplication, Division, logical: and, or, not
comparison operators; equal to, not equal to, less
than, greater than)
▪ Control structures (sequence, selection, loops)
• designing programmes that use control structures
o Debugging programmes
2
- Programmers are also called software developers or software engineers
Algorithm
- This is a design of a computer program prior to the implementation
- Algorithms are also referred to as program blue prints
Source code
- This is set of instructions written by a programmer that are not
converted into machine readable form
- This is usually a text file written in programming languages like BASIC,
Pascal or C++
Object code
- This is set of instructions that have been converted into machine
readable form
- Assemblers, interpreters and compliers are used to convert a source
code into an object code
Assembler
- Converts assembly language into machine readable form
Interpreters
- Converts source code into an object code statement by statement
allowing CPU to execute one line at a time
- Interpreted line is not stored in the computer memory hence every time
the program is needed for execution, each line has to be interpreted
- Interpreters were mostly used by early computers that did not have
memory
3
Compiler
- Converts entire source code into object code
- The process of converting a source code into an object code by
compilers is called compilation
- The following are the steps of compilation process
4
Differences between interpreters and compilers
Interpreters Compilers
1. Translate the source code 1. Translate the entire source
to object code one code at once before execution
statement at a time
2. Translate the program each 3. Complied program (object
time it is to run hence code) can be saved on a
slower than compliers storage media and run as
required, hence they are faster
than interpreters
Interpreted object code takes less Compiled programs require more me
memory compared to compiled mory since object files are larger
program
5
- Programmers have to design their code by hand then transfer it to a
computer by using a punch card, punch tape or flicking switches.
- There is no need to translate the code and it will run straight away.
This may sound rather archaic,
Advantages of Machine language
i. Code can be fast and efficient
ii. Code can make use of specific processor features such as special
registers
i. Lack of portability
6
- To convert an assembly code program into object code to run on a
computer requires an Assembler and each line of assembly can be
replaced by the equivalent one line of object (machine) code
Lack of portability
7
NB: first and second generation programming languages are referred to Low
level Languages because computers can understand their code with minimal
effort.
8
v. C :
o suitable for developing operating systems
vi. Ada
o suitable for developing military, industrial and real time systems
Would output: 8
9
- Examples of 4GLs includes
i. Structured Query Language (SQL),
ii. Oracle Reports
iii. CSS
An example of code written using SQL is as follows
Scripting Languages
- A scripting language is a programming language designed for
integrating and communicating with other programming languages.
- Some of the most widely used scripting languages are
i. JavaScript,
ii. VBScript,
iii. PHP,
iv. Perl,
v. Python,
vi. Ruby,
vii. ASP and
viii. Tcl.
10
- Since a scripting language is normally used in conjunction with another
programming language, they are often found alongside HTML, Java or
C++.
11
Components of HTML code
Consider the following HTML code
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
</body>
</html>
Code Explanation
12
• The <body> element contains the visible page content
• The <h1> element defines a large heading
• The <p> element defines a paragraph
1. High level languages are programmer friendly. They are easy to write,
debug and maintain.
2. It provides higher level of abstraction from machine languages.
3. It is machine independent language.
4. Easy to learn.
5. Less error prone, easy to find and debug errors.
6. High level programming results in better programming productivity.
13
- A program development process consists of various steps that are
followed to develop a computer program.
- These steps are followed in a sequence in order to develop a
successful and beneficial computer program.
- Following is the brief description about program development process.
problem
definition
Program Review
Algorithm Design
and Maintenance
Program Testing
Program Coding
and debugging
14
3. Coding or Writing The Program
4. Program Testing Execution
5. Debugging
6. Program review and maintenance
Designing an Algorithm
15
Coding or Writing the Program
- The next step after designing the algorithm is to write the program in
a high-level language.
- This process is known as coding.
Program Testing
i. Syntax error
16
The following steps are used
b. Debugging
c. Test data
- Carry out trial runs using test data to check for logical run-time errors
- Achieved by entering valid and invalid input to test whether the
program produces desired result
Debugging
17
Final Documentation
1. Portability:
- Portability refers to the ability of an application to run on different
platforms (operating systems) with or without minimal changes.
2. Readability:
18
3. Efficiency:
- Every program requires certain processing time and memory to
process the instructions and data.
- As the processing power and memory are the most precious resources
of a computer, a program should be laid out in such a manner that it
utilizes the least amount of memory and processing time.
4. Structural:
5. Flexibility:
19
Hence, the payroll application should be flexible enough to incorporate
all the changes without having to reconstruct the entire application.
6. Generality:
7. Documentation:
20
Framework and the common language runtime with the productivity
benefits that are the hallmark of Visual Basic.
- VB.NET is implemented by Microsoft's .NET framework. Therefore, it
has full access to all the libraries in the .Net Framework. It's also
possible to run VB.NET programs on Mono, the open-source alternative
to .NET, not only under Windows, but even Linux or Mac OSX.
The following tools are required to set up environment for writing and
running Visual basic programs
21
1. The .Net Framework
i. Windows applications
ii. Web applications
iii. Web services
NB : for you to start programming in VB, make sure one of the above IDE
is installed in your computer
Structure of VB program
22
To understand structure of VB program, lets consider the following example
of simple program written in VB.net
• Namespace declaration
• A class or module
• One or more procedures
• Variables
• The Main procedure
• Statements & Expressions
• Comments
Let us look at a simple code that would print the words "Hello World" −
Imports System
Module Module1
'This program will display Hello World
Sub Main()
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
23
End Module
When the above code is compiled and executed, it produces the following
result −
Hello, World!
- The first line of the program Imports System is used to include the
System namespace in the program.
- The next line has a Module declaration, the module Module1. VB.Net
is completely object oriented, so every program must contain a module
of a class that contains the data and procedures that your program
uses.
- Classes or Modules generally would contain more than one procedure.
Procedures contain the executable code, or in other words, they define
the behavior of the class. A procedure could be any of the following −
o Function
o Sub
o Operator
o Get
o Set
24
o AddHandler
o RemoveHandler
o RaiseEvent
- The next line( 'This program) will be ignored by the compiler and it has
been put to add additional comments in the program.
- The next line defines the Main procedure, which is the entry point for
all VB.Net programs. The Main procedure states what the module or
class will do when executed.
- The Main procedure specifies its behavior with the statement
- The last line Console.ReadKey() is for the VS.NET Users. This will
prevent the screen from running and closing quickly when the program
is launched from Visual Studio .NET.
If you are using Visual Studio.Net IDE, take the following steps −
25
• Choose Console Application.
• Specify a name and location for your project using the Browse button,
and then choose the OK button.
• The new project appears in Solution Explorer.
• Write code in the Code Editor.
• Click the Run button or the F5 key to run the project. A Command
Prompt window appears that contains the line Hello World.
You can compile a VB.Net program by using the command line instead of the
Visual Studio IDE −
- First of all, launch Microsoft Visual Basic 6 compiler that you have
installed earlier.
Copyright © learnmalawi | All rights reserved
26
- In the New Project Dialog , choose Standard EXE to enter Visual Basic
6 integrated development environment.
- 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 below
- The top of the source code window consists of a list of objects and
their associated events or procedures.
27
- In the source code window, the object displayed is Form1 and the
associated procedure is Load.
- When you click on the object box, the drop-down list will display a list
of objects you have inserted into your form.
- Here, you can see 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
- Some of the procedures associated with the object Form1 are Activate,
Click, DblClick (which means Double-Click) , DragDrop, keyPress and
more.
28
- Each object has its own set of procedures.
- You can always select an object and write codes for any of its
procedure in order to perform certain tasks.
- You do not have to worry about the beginning and the end statements
- Just key in the lines in between the above two statements exactly as
are shown here.
29
- When you press F5 to run the program, you will be surprised that
nothing showed up
- .In order to display the output of the program, you have to add the
Form1.show statement or you can just use Form_Activate (
) event procedure
- 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 and you
will get the output as
Example 1
Form1.show
End Sub
Example 2
Print 20 + 10
Print 20 - 10
30
Print 20 * 10
Print 20 / 10
End Sub
31
You can also use the + or the & operator to join two or more texts (string)
together
Example 3
Private Sub
A = "Tom"
B = "likes"
C = "to"
D = "eat"
E = "burger"
Print A + B + C + D + E
32
End Sub
Example 4
Private Sub
A = "Tom"
B = "likes"
C = "to"
D = "eat"
E = "burger"
Print A & B & C & D & E
End Sub
33
Steps in Building a Visual Basic Application
Step 1: Design the interface by adding controls to the form and set their
properties
34
- We will place two command buttons and a label on the form. One of
the command buttons will be used to change the background color
while the other one will be used to change the foreground color.
- The Label is for displaying the foreground color. There are two events
here, change background color and change foreground color.
Therefore, we need to write code for the two event procedures.
• To make the program more interesting, we will use the Rnd() function,
the Int() function and the RGB codes to change the color 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 color.
- 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. Do not worry about the jargons, you will learn them in
later.
35
• Form1-MyForm
• Label1-LblMessage
• Command1-cmd_bgColor
• Command2-cmd_fgColor
36
b = Int(Rnd() * 256)
Lbl_Msg.ForeColor = RGB(r, g, b)
End Sub
- When you run the program, each time you press on the 'Change
Background Color' button, you will see different background color.
- Similarly, each time you press on the 'Change Foreground Color', you
will see the message on the Label changes color. The output is shown
below
37
- You can set the properties of the controls in the properties window or
at runtime.
- 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.
38
- For example, in order to change the caption, just highlight Form1
under the name Caption and change it to other names.
- You may also alter the appearance of the form by setting it to 3D or
flat, change its foreground and background color, change the font type
and font size, enable or disable, minimize and maximize buttons and
more.
- You can also change the properties at runtime to give special effects
such as change of color, shape, animation effect and so on.
39
Example 6 Program to change background color
This example changes the background colour of the form using the
BackColor property.
40
The TextBox
- 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 8
- In this program, two text boxes are inserted into the form together
with a few labels.
41
- 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.
42
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, it can also be used to
display outputs.
- Caption, it can display text and numeric data. You can change its
caption in the properties window and also at runtime.
43
- The most common event associated with the command button is the
Click event, and the syntax for the procedure is
44
Run the program and enter a password, then click on the Show Password
button to reveal the password, as shown below.
- You can also reveal the password by setting the PasswordChr property
back to normal mode, as follows:
The PictureBox
- 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.
45
- 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")
In this program, insert a command button and a picture box. Enter the
following code:
* You must ensure the path to access the picture is correct. Besides that,
the image in the picture box is not resizable. The output is shown below
46
The Image Control
Image1.Picture=LoadPicture ("C:\VBprogram\Images\grape.gif")
47
Example :: Loading Image
* Note the difference between the image in Figure 3.5 and Figure 3.6.
The ListBox
- The function of the ListBox is to present a list of items where the user
can click and select the items from the list.
48
- In order to add items to the list, we can use the AddItem method.
For example, if you wish to add a number of items to list box 1, you
can key in the following statements
Example
Private Sub Form_Load ( )
List1.AddItem “Lesson1”
List1.AddItem “Lesson2”
List1.AddItem “Lesson3”
List1.AddItem “Lesson4”
End Sub
The Output
- The items in the list box can be identified by the ListIndex property, the
value of the ListIndex for the first item is 0, the second item has a ListIndex
1, and the third item has a ListIndex 2 and so on
Copyright © learnmalawi | All rights reserved
49
The ComboBox
- 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.
- In order to add items to the list, you can also use the AddItem
method.
- For example, if you wish to add a number of items to Combo box 1,
you can key in the following statements
Example
Private Sub Form_Load ( )
Combo1.AddItem "Item1"
Combo1.AddItem "Item2"
Combo1.AddItem "Item3"
Combo1.AddItem "Item4"
End Sub
50
The Output
The CheckBox
- 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.
- You can include the statements Check1.Value=1 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, the program in Example below will show which items are
selected in a message box.
Example
Private Sub Cmd_OK_Click()
If Check1.Value = 1 And Check2.Value = 0 And Check3.Value = 0 Then
MsgBox "Apple is selected"
Copyright © learnmalawi | All rights reserved
51
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
52
The Output
The OptionButton
- The OptionButton control also lets the user selects one of the choices.
However, two or more Option buttons must work together because as
one of the option buttons is selected, the other Option button will be
unselected
- In fact, only one Option Box can be selected at one time.
- When an option box is selected, its value is set to “True” and when it
is unselected; its value is set to “False”.
Example
53
- We insert three option buttons and change their captions to "Red
Background","Blue Background" and "Green Background" respectively.
- Next, insert a command button and change its name to cmd_SetColor
and its caption to "Set Background Color". Now, click on the command
button and enter the following code in the code window:
Run the program, select an option and click the "Set Background Color"
produces the output, as shown below
54
The Shape Control
- In the following example, the shape control is placed in the form
together with six OptionButtons.
- To determine the shape of the shape control, we use the shape
property.
- The property values of the shape control are 0, 1, and 2,3,4,5 which
will make it appear as a rectangle, a square, an oval shape, a circle, a
rounded rectangle and a rounded square respectively.
Example
55
- clicking the paste button, a popup dialog will ask you whether you
wish to create a control array, select yes.
- The control array can be accessed via its index value, MyOtion(Index.
In addition, we also insert a shape control.
- Now, enter the code in the code window. We use the If..Then..Else
program structure to determine which option button is selected by the
user. Private Sub MyOption_Click(Index As Integer)
If Index = 0 Then
MyShape.Shape = 0
ElseIf Index = 1 Then
MyShape.Shape = 1
ElseIf Index = 2 Then
MyShape.Shape = 2
ElseIf Index = 3 Then
MyShape.Shape = 3
ElseIf Index = 4 Then
56
MyShape.Shape = 4
ElseIf Index = 5 Then
MyShape.Shape = 5
End If
End Sub
- Run the program and you can change the shape of the shape control
by clicking one of the option buttons.
- The output is shown in Figure below.
Figure 3.
The DriveListBox
57
- When you place this control into the form and run the program, you
will be able to select different drives from your computer as shown
below
The DirListBox
58
DirListBox
The FileListBox
- You can coordinate the Drive List Box, the Directory List Box and the
File List Box to search for the files you want.
Event Procedure
Copyright © learnmalawi | All rights reserved
59
- For each event, you need to write an event procedure so that it can
perform an action or a series of actions.
- To start writing code for an event procedure, you need to double-click
an object to enter the VB code window.
- For example, if you want to write code for the event of clicking a
command button, you double-click the command button and enter the
codes in the event procedure that appears in the code window, as
shown below
Figure 4.1
60
Private Sub Command1_Click
VB Statements
End Sub
Object.Property
61
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
Private Sub Command1_click()
Label1.Visible=false
Label2.Visible=True
Text1.Text="You are correct!"
End sub
Example
Private Sub Command1_click()
Label1.Caption="Welcome"
Image1.visible=true
End sub
Example
Private Sub Command1_click()
Pictuire1.Show=true
Timer1.Enabled=True
Lable1.Caption="Start Counting"
Copyright © learnmalawi | All rights reserved
62
End sub
Example : A Counter
The Code
Dim n As Integer
Private Sub cmd_StartCount_Click()
Copyright © learnmalawi | All rights reserved
63
Timer1.Enabled = True
End Sub
64
The Output
- This program display a message whether the label is being click once
or click twice.
- In this program, insert a label and rename it as MyLabel and change
its caption to "CLICK ME". Next, key in the following codes:
65
The out
- Running the program and click the label once, the "CLICK ME" caption
will change to "You Click Me Once". If you click the label twice, the
"CLICK ME" caption will change to "You Click Me Twice!".
NB: In Visual Basic, most of the syntaxes resemble the English language.
Among the syntaxes are Print, If…Then….Else….End If, For…Next,
Select Case…..End Select , End and Exit Sub. For example, Print “
Visual Basic” is to display the text Visual Basic on screen and End is to end
the program.
- Program code that involves calculations is fairly easy to write, just like
what you do in mathematics. However, in order to write an event
66
procedure that involves calculations, you need to know the basic
arithmetic operators in VB as they are not exactly the same as the
normal operators , except for + and - .
Example
Private Sub Form_Activate()
Text3.text=text1.text+text2.text
End Sub
67
- When you run the program above and enter 12 in textbox1 and 3 in
textbox2 will give you a result of 123, which is wrong.
- It is because VB treat the numbers as string and so it just joins up the
two strings. On the other hand,
Example
Private Sub Form_Activate()
Text3.text=val(text1.text)+val(text2.text)
End Sub
- Running the above program code will give you the correct result, i.e.,
15.
- VB6 classifies the information into two major data types, they are the
- Numeric data types are types of data that consist of numbers that can
be computed mathematically with standard operators.
- Examples of numeric data types are
o height,
Copyright © learnmalawi | All rights reserved
68
o weight,
o share values,
o the price of goods,
o monthly bills,
o fees and others.
69
-3.402823E+38 to -1.401298E-45 for negative
Single 4 bytes values 1.401298E-45 to 3.402823E+38 for
positive values.
-1.79769313486232e+308 to -
4.94065645841247E-324 for negative values
Double 8 bytes
4.94065645841247E-324 to
1.79769313486232e+308 for positive values.
-922,337,203,685,477.5808 to
Currency 8 bytes
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).
70
Nonnumeric Data Types
Length of
String(fixed length) 1 to 65,400 characters
string
String(variable Length + 10
0 to 2 billion characters
length) bytes
January 1, 100 to
Date 8 bytes
December 31, 9999
- Literals are values that you assign to data. In some cases, we need to
add a suffix behind a literal so that VB can handle the calculation more
accurately.
- For example, we can use num=1.3089# for a Double type data. Some
of the suffixes are displayed in Table below
71
Suffixes for Literals
& Long
! Single
# Double
@ Currency
memberName="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#
Managing Variables
72
- In term of VB, variables are areas allocated by the computer memory
to hold data. Like the mail boxes, each variable must be given a name.
- To name a variable in Visual Basic, you have to follow a set of rules.
i. Variable Names
- The following are the rules when naming the variables in Visual Basic
Examples of valid and invalid variable names are displayed in Table below
My_Car My.Car
73
Declaring Variables Explicitly
Example
Dim password As String
Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
74
Dim doDate As Date
Dim password As String, yourName As String, firstnum As Integer
For example,
75
Scope of Declaration
- Other than using the Dim keyword to declare the data, you can also
use other keywords to declare the data.
- Three other keywords are
i. private ,
ii. static and
iii. public.
76
- 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.
Constants
- Constants are different from variables in the sense that their values do
not change during the running of the program.
Declaring a Constant
Example
77
- In addtion, 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 we 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
End Sub
78
The Output
Variable=Expression
79
- 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
- Operators are symbols that are used to manipulate inputs from users
and to generate results,
- We need to use various mathematical operators
80
- . In Visual Basic, except for + and -, the symbols for the operators are
different from normal mathematical operators, as shown in Table
below
Arithmetic Operators
^ Exponential 2^4=16
* Multiplication 4*3=12,
/ Division 12/4=3
"Visual"&"Basic"="Visual
+ or & String concatenation
Basic"
Example
Private Sub Command1_Click()
firstName = Text1.Text
secondName = Text2.Text
yourName = secondName +"" + firstName
Copyright © learnmalawi | All rights reserved
81
Label1.Caption = yourName
End Sub
Example
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 above example , 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.
82
Example : Easy Math
- This is a simple math drill program where the user enter two numbers
and calculate its sum. The program will tell him whether the answer is
right or wrong.
- To add some gist to the program, the user needs to enter the
password before he or she can proceed.
The Code
Dim password As String
Dim yourName As String
Dim firstnum As Integer
Dim secondnum As Integer
Dim total As Integer
Dim doDate As Date
83
Label1.Visible = False
Command1.Visible = False
Else
userpass.Text = ""
userpass.SetFocus
End If
End Sub
3.'
Private Sub Form_Load()
password = "liewxun"
End Sub
End Sub
84
The Output
85
- 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 below
Conditional Operators
Operator Meaning
= Equal to
Logical Operators
86
Logical Operators
Operator Description
- You can also compare strings with the operators. However, there are
certain rules to follow where upper case letters are less than lowercase
letters, and number are less than letters.
CONDITIONAL STATEMENTS
If conditions Then
VB expressions
Else
VB expressions
87
End If
Example
The Code
Private Sub OK_Click()
Dim username, password As String
username = "John123"
password = "qwertyupi#@"
88
End Sub
The Output
Example
<5000 0
Copyright © learnmalawi | All rights reserved
89
5000-9999 5
1000-14999 10
15000-19999 15
The Code
90
comm = 0
End If
LblComm.Caption = Format(comm, "$#,##0.00")
End Sub
The Output
- This is a guess a number game where the user key in a number and
see check whether the answer is correct.
- This program will provide a hint whether the number is too small or
too big.
- After a number of trial, the user should get the right answer.
- The program employ the If..Then..Else technique to check whether the
entry is correct.
91
The Code
'Guess a Number
Const realNumber = 99
Dim userNumber As Integer
userNumber = entry.Text
If userNumber > realNumber Then
entry.Text = ""
entry.SetFocus
Else
92
hint.Caption = "Congratulation, your number is correct"
End If
End Sub
IIf(x, y, z)
Example
Private Sub CmdNumeric_Click()
Dim x, y, a, b, ans As Double
x = InputBox("Enter a number")
y = InputBox("Enter another number")
a = Val(x)
Copyright © learnmalawi | All rights reserved
93
b = Val(y)
94
The Interface
- If you click test string and enter the first word long and the second
word short, the logical condition is true, hence the word long will be
displayed, as shown in Figure 7.5.
- If you click test numeric and enter the first number 200 and the
second number 40, the logical condition is false, hence the second
expression will be executed, which is 20x40=800, as shown below
Select Cases
95
control structure can handle conditions with multiple outcomes in an
easier manner than the If...Then...ElseIf control structure.
- The syntax of the Select Case control structure is shown below:
Case value2
Block of one or more VB Statements
Case Else
Block of one or more VB Statements
End Select
Example
Dim grade As String
Private Sub Compute_Click( )
grade=txtgrade.Text
Select Case grade
Case "A"
result.Caption="High Distinction"
Case "A-"
result.Caption="Distinction"
Case "B"
result.Caption="Credit"
Case "C"
result.Caption="Pass"
Case Else
result.Caption="Fail"
End Select
End Sub
96
Example
Dim mark As Single
Private Sub Compute_Click()
'Examination Marks
mark = mrk.Text
Select Case mark
Case Is >= 85
comment.Caption = "Excellence"
Case Is >= 70
comment.Caption = "Good"
Case Is >= 60
comment.Caption = "Above Average"
Case Is >= 50
comment.Caption = "Average"
Case Else
comment.Caption = "Need to work harder"
End Select
End Sub
Example
97
Case 70 to 84
comment.Caption = "Good"
Case Else
comment.Caption ="Excellence"
End Select
End Sub
The Code
Dim Secret_Number As Integer
Case Else
Beep
MsgBox ("Your number is correct, congratulation!")
End Select
End Sub
Copyright © learnmalawi | All rights reserved
98
Private Sub Form_Load()
Secret_Number = 1 + Int(6 * Rnd)
End Sub
Looping
- These are control structures that are used to write a Visual Basic
procedure that allows the program to run repeatedly until a condition
or a set of conditions is met
- Looping is a very useful feature of Visual Basic because it makes
repetitive works easier.
- There are three kinds of loops in Visual Basic,
i. Do...Loop ,
ii. For.......Next loop
iii. While.....Wend Loop
The Do Loop
a)
Do While condition
Block of one or more VB statements
Loop
b)
Do
Block of one or more VB statements
Copyright © learnmalawi | All rights reserved
99
Loop While condition
c)
Do Until condition
Block of one or more VB statements
Loop
d)
Do
Block of one or more VB statements
Loop Until condition
Example
Do while
counter <=1000
num.Text=counter
counter =counter+1
Loop
* The above example will keep on adding until counter > 1000
Do
counter=counter+1
Loop until counter>1000
Example
Dim sum, n as Integer
Private Sub Form_Activate()
List1.AddItem "n" & vbTab & "sum"
Copyright © learnmalawi | All rights reserved
100
Do
n=n+1
sum=sum+n-resize
List1.AddItem n & vbTab & sum
If n=100 Then
Exit Do
End If
Loop
End Sub
Explanation
Next
101
Example
Example
For counter=1000 to 5 step -5
counter=counter-10
If counter<50 then
Exit For
Else
Print "Keep Counting"
End If
Next
Example
Private Sub Form_Activate( )
For n=1 to 10
If n>6 then
Exit For
Else
Copyright © learnmalawi | All rights reserved
102
Print n
Enf If
Next
End Sub
- Sometimes the user might want to get out from the loop before the
whole repetitive process is executed, the command to use is Exit For.
To exit a For….Next Loop, you can place the Exit For statement within
the loop; and it is normally used together with the If…..Then…
statement.
While condition
Statements
Wend
The above loop means that while the condition is not met, the loop will go
on. The loop will end when the condition is met. Let’s examine the program
listed in example below
Example
Dim sum, n As Integer
Private Sub Form_Activate()
List1.AddItem "n" & vbTab & "sum"
While n <> 100
n=n+1
Sum = Sum + n
List1.AddItem n & vbTab & Sum
Copyright © learnmalawi | All rights reserved
103
Wend
End Sub
REFERENCES
104
Fishpool, B Information technology level 1: foundation diploma. Pearson
Company.
Gay, G Blades, R (2009). Oxford information technology for CSEC. New York:
Oxford University
Press.
Internet
105