0% found this document useful (0 votes)
9 views

6 Programming Fundamentals(1)-1

programming

Uploaded by

mdeenyale
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)
9 views

6 Programming Fundamentals(1)-1

programming

Uploaded by

mdeenyale
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/ 105

CHAPTER 6: Programming Fundamentals

Objectives

By the end of this chapter, the student should be able to:

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)

Copyright © learnmalawi | All rights reserved

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

Definitions of terms in programming


computer program
- Set of instructions written using a programming language to tell
computer to perform a task
- A program is like a recipe containing a list of ingredients referred to as
variables and list of instructions ( statements) that instructs a computer
what to do with the variables
Programming language
- A formal language that specifies syntax and semantic rules for writing a
computer programs
- Examples of programming languages include Pascal, FORTRAN and
COBOL
Computer programming
- This is a process of writing a computer program using programming
language
- The person who writes programs is referred to as programmer
Copyright © learnmalawi | All rights reserved

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

Copyright © learnmalawi | All rights reserved

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

a. Preprocess – source code is prepared for the conversion


b. Compile – source code is changed into an object code
c. Linking – libraries are added to an object code to generated an
executable file which is loaded into RAM and executed by CPU

Copyright © learnmalawi | All rights reserved

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

A Brief History of Programming Languages


- Programming languages have been developed in stages called
generations
1. The first generation programming languages (Machine
Language
- The first generation program language is pure machine code, that is

just ones and zeros, e.g.

Copyright © learnmalawi | All rights reserved

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

Drawbacks of Machine Language

i. Lack of portability

- Code cannot be ported to other systems

ii. Code is difficult to edit and update since very cumbersome to be


understood by human beings

Second generation programming (Assembly Language)

- Second-generation programming languages are a way of describing


Assembly code which you may have already met.
- Uses codes resembling English, programming becomes much easier.
- The usage of these mnemonic codes such as LDA for load and STA for
store means the code is easier to read and write.

Copyright © learnmalawi | All rights reserved

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

Advantages of second generation languages (Assembly Language)

i. Code can be fast and efficient


ii. Code can make use of specific processor features such as special
registers
iii. As it is closer to plain English, it is easier to read and write when
compared to machine code

Drawbacks of Assembly Language

Lack of portability

- Code cannot be ported to other systems i.e a code only runs on a


machine where it was written

Copyright © learnmalawi | All rights reserved

7
NB: first and second generation programming languages are referred to Low
level Languages because computers can understand their code with minimal
effort.

Third generation Programming Language (High Level Language)

- Also called structured programming languages


- Structured programming languages has ability to break down a
program into smaller components called modules, each performing a
particular task
- 3GLs are close to human language hence can be read and understood
by people who are experts in programming.
Examples of 3GLs include
i. Pascal
o Enable teaching and learning structuall programming to be easy
ii. FOTRAN (FORmula TRANslator)
o For writing programs that solve scientific, mathematics and
engineering problems
iii. COBOL : (Common Business – Oriented Language)
o Suitable for developing programs that solve business problems
iv. BASIC :(Beginners All-purpose Symbolic Instruction Code)
o Suitable for developing business and education systems

Copyright © learnmalawi | All rights reserved

8
v. C :
o suitable for developing operating systems
vi. Ada
o suitable for developing military, industrial and real time systems

NB Third generation (High Level Languages) codes are imperative.


- Imperative means that code is executed line by line, in sequence. For
example:

Would output: 8

Fourth generation Programming Language

- Fourth-generation languages are designed to reduce programming


effort and the time it takes to develop software, resulting in a
reduction in the cost of software development.
- They are not always successful in this task, sometimes resulting in
inelegant and hard to maintain code.
Copyright © learnmalawi | All rights reserved

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.

Copyright © learnmalawi | All rights reserved

10
- Since a scripting language is normally used in conjunction with another
programming language, they are often found alongside HTML, Java or
C++.

HTML (HyperText Markup Language)

- is the standard markup language for creating Web pages.


- HTML stands for Hyper Text Markup Language
- HTML describes the structure of a Web page
- HTML consists of a series of elements
- HTML elements tell the browser how to display the content
- HTML elements are represented by tags
- HTML tags label pieces of content such as "heading", "paragraph",
"table", and so
- Browsers do not display the HTML tags, but use them to render the
content of the page

Copyright © learnmalawi | All rights reserved

11
Components of HTML code
Consider the following HTML code
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>

Code Explanation

• The <!DOCTYPE html> declaration defines this document to be


HTML5
• The <html> element is the root element of an HTML page
• The <head> element contains meta information about the document
• The <title> element specifies a title for the document

Copyright © learnmalawi | All rights reserved

12
• The <body> element contains the visible page content
• The <h1> element defines a large heading
• The <p> element defines a paragraph

Advantages of High level language

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.

Disadvantages of High level language

1. It takes additional translation times to translate the source to machine


code.
2. High level programs are comparatively slower than low level programs.
3. Compared to low level programs, they are generally less memory
efficient.
4. Cannot communicate directly with the hardware.

Program development process


Copyright © learnmalawi | All rights reserved

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

- A programmer has to go through the following stages to develop a


computer program:
1. Defining and Analyzing The Problem
2. Designing The Algorithm
Copyright © learnmalawi | All rights reserved

14
3. Coding or Writing The Program
4. Program Testing Execution
5. Debugging
6. Program review and maintenance

Defining and Analyzing The Problem

- In this step, a programmer studies the problem.


- He decides the best way to solve these problems.
- Studying a problem is also necessary because it helps a programmer
to decide about the following things:
o The facts and figures which are necessary for developing the
program.
o way in which the program will be designed
o Also, the language in which the program will be most suitable.
o What is the desired output and in which form it is needed, etc

Designing an Algorithm

- An algorithm is a sequence of steps that must be carried out before a


programmer starts preparing his program.
- The programmer designs an algorithm to help visual possible
alternatives in a program also.

Copyright © learnmalawi | All rights reserved

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

- The process of executing the program to find out errors or bugs is


called test execution.
- It helps a programmer to check the logic of the program. It also
ensures that the program is error-free and workable.
- The following are common types of errors that might be encountered

i. Syntax error

- Due to improper use of language


- Also called grammatical errors
- These errors can be detected by a compiler

ii. Logical error

- Due to improper use of Logic in a program


- Can not be detected by a compiler
- A program runs successfully but gives a wrong output

Tracing an error in a program


Copyright © learnmalawi | All rights reserved

16
The following steps are used

a. Dry-run (desk check)

- Uses trace table to check whether an algorithm has errors


- Usually dry run checks for logical errors

b. Debugging

- Uses debug utility in an editor to check for syntax errors

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

- Debugging is a process of detecting, locating and correcting the bugs


in a program. It is performed by running the program again and again.

Program review and maintenance


- This is continuous updating and fixing of program errors after
installation
- Maintenance of a program stops only when a program has been
replace or if it becomes unusable

Copyright © learnmalawi | All rights reserved

17
Final Documentation

- When the program is finalized, its documentation is prepared. Final


documentation is provided to the user.
- It guides the user how to use the program in the most efficient way.
- Furthermore, another purpose of documentation is to allow other
programmers to modify the code if necessary.
- Documentation should also be done in each step during the
development of the program.

Characteristics of a good program

A good computer program should have following characteristics:

1. Portability:
- Portability refers to the ability of an application to run on different
platforms (operating systems) with or without minimal changes.

2. Readability:

- The program should be written in such a way that it makes other


programmers or users to follow the logic of the program without much
effort.
- If a program is written structurally, it helps the programmers to
understand their own program in a better way.
Copyright © learnmalawi | All rights reserved

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:

- To develop a program, the task must be broken down into a number


of subtasks.
- These subtasks are developed independently, and each subtask is able
to perform the assigned job without the help of any other subtask.
- If a program is developed structurally, it becomes more readable, and
the testing and documentation process also gets easier.

5. Flexibility:

- A program should be flexible enough to handle most of the changes


without having to rewrite the entire program.
- Most of the programs are developed for a certain period and they
require modifications from time to time.
- For example, in case of payroll management, as the time progresses,
some employees may leave the company while some others may join.

Copyright © learnmalawi | All rights reserved

19
Hence, the payroll application should be flexible enough to incorporate
all the changes without having to reconstruct the entire application.

6. Generality:

- Apart from flexibility, the program should also be general.


- Generality means that if a program is developed for a particular task,
then it should also be used for all similar tasks of the same domain.
- For example, if a program is developed for a particular organization,
then it should suit all the other similar organizations.

7. Documentation:

- Documentation is one of the most important components of an


application development.
- Even if a program is developed following the best programming
practices, it will be rendered useless if the end user is not able to fully
utilize the functionality of the application.
- A well-documented application is also useful for other programmers
because even in the absence of the author, they can understand it.

Programming in Visual Basic


- VB.Net is a simple, modern, object-oriented computer programming
language developed by Microsoft to combine the power of .NET

Copyright © learnmalawi | All rights reserved

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 reasons make VB.Net a widely used professional language −

• Modern, general purpose.


• Object oriented.
• Component oriented.
• Easy to learn.
• Structured language.
• It produces efficient programs.
• It can be compiled on a variety of computer platforms.
• Part of .Net Framework.

Setting environment for VB.net programming

The following tools are required to set up environment for writing and
running Visual basic programs

Copyright © learnmalawi | All rights reserved

21
1. The .Net Framework

- The .Net framework is a revolutionary platform that helps you to write


the following types of applications

i. Windows applications
ii. Web applications
iii. Web services

2. Integrated Development Environment (IDE) For VB.Net

- Microsoft provides the following development tools for VB.Net


programming −

• Visual Studio 2010 (VS)


• Visual Basic 2010 Express (VBE)
• Visual Web Developer

NB : for you to start programming in VB, make sure one of the above IDE
is installed in your computer

Structure of VB program

Copyright © learnmalawi | All rights reserved

22
To understand structure of VB program, lets consider the following example
of simple program written in VB.net

VB.Net Hello World Example

A VB.Net program basically consists of the following parts −

• 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

Copyright © learnmalawi | All rights reserved

23
End Module

When the above code is compiled and executed, it produces the following
result −

Hello, World!

Let us look various parts of the above program –

- 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

Copyright © learnmalawi | All rights reserved

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

Console.WriteLine("Hello World") WriteLine is a method of the


Console class defined in the System namespace. This statement
causes the message "Hello, World!" to be displayed on the screen.

- 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.

Compile & Execute VB.Net Program

If you are using Visual Studio.Net IDE, take the following steps −

• Start Visual Studio.


• On the menu bar, choose File → New → Project.
• Choose Visual Basic from templates
Copyright © learnmalawi | All rights reserved

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 −

• Open a text editor and add the above mentioned code.


• Save the file as helloworld.vb
• Open the command prompt tool and go to the directory where you
saved the file.
• Type vbc helloworld.vb and press enter to compile your code.
• If there are no errors in your code the command prompt will take you
to the next line and would generate helloworld.exe executable file.
• Next, type helloworld to execute your program.
• You will be able to see "Hello World" printed on the screen.

.1 Creating Your First Application

- 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.

Copyright © learnmalawi | All rights reserved

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.

Copyright © learnmalawi | All rights reserved

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

(i.e. Private Sub Form_Load.......End Sub.);

- Just key in the lines in between the above two statements exactly as
are shown here.

Copyright © learnmalawi | All rights reserved

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

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

Copyright © learnmalawi | All rights reserved

30
Print 20 * 10
Print 20 / 10

End Sub

Output for example 1

Output for example 2

Copyright © learnmalawi | All rights reserved

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

Copyright © learnmalawi | All rights reserved

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

OUTPUT for example 3 and 4

Copyright © learnmalawi | All rights reserved

33
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 5 Changing Background and Foreground Color at Random

- In this example, we want to show you how to write code to change


the background and the foreground color randomly.
Copyright © learnmalawi | All rights reserved

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.

1. Now, rename the controls as follows:

Copyright © learnmalawi | All rights reserved

35
• Form1-MyForm
• Label1-LblMessage
• Command1-cmd_bgColor
• Command2-cmd_fgColor

2. Next, change the caption of the Label to "Please Change My Color".

- In addition, change the caption of Command1 button to "Change


Background Color" and change the caption of Command2 button to
"Change Foreground Color"

3. 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)
Copyright © learnmalawi | All rights reserved

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

The Control Properties

- Before writing an event procedure for the control to response to an


event, you have to set certain properties for the control to determine
its appearance and how will it work with the event procedure.
Copyright © learnmalawi | All rights reserved

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.

Copyright © learnmalawi | All rights reserved

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.

Copyright © learnmalawi | All rights reserved

39
Example 6 Program to change background color

This example changes the background colour of the form using the
BackColor property.

Private Sub Form_Load()


Form1.Show
Form1.BackColor = &H000000FF&
End Sub

Example 7: 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

Handling some of the common Controls

Below is the VB6 toolbox that shows the basic controls.

Copyright © learnmalawi | All rights reserved

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.

Copyright © learnmalawi | All rights reserved

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.

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

Copyright © learnmalawi | All rights reserved

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.

- 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.

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 click on
it.

Copyright © learnmalawi | All rights reserved

43
- 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

Example 9 A Simple Password Cracker

- In this program, we want to crack a secret passoword entered by the


user.
- In the design phase, insert a command button and change its name to
cmd_ShowPass.
- Next, insert a TextBox and rename it as TxtPassword and delete Text1
from the Text property.
- Besides that, set its PasswordChr to *. Now, enter the following code
in the code window.

Private Sub cmd_ShowPass_Click()


Dim yourpassword As String
yourpassword = Txt_Password.Text
MsgBox ("Your password is: " & yourpassword)
End Sub

Copyright © learnmalawi | All rights reserved

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:

Private Sub cmd_ShowPass_Click()


Dim yourpassword As String
Txt_Password.PasswordChar = ""
End Sub

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.

Copyright © learnmalawi | All rights reserved

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")

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("C:\Users\admin.DESKTOP-
G1G4HEK\Documents\My Websites\vbtutor\vb6\images\uranus.jpg")
End Sub

* 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

Copyright © learnmalawi | All rights reserved

46
The Image Control

- The Image Control is another control that handles images and


pictures.
- It functions almost identically to the pictureBox. However, there is one
major difference, the image in an Image Box is stretchable, which
means it can be resized.
- This feature is not available in the PictureBox. Similar to the Picture
Box, it can also use the LoadPicture method to load the picture.
- For example, the statement loads the picture grape.gif into the image
box.

Image1.Picture=LoadPicture ("C:\VBprogram\Images\grape.gif")

Copyright © learnmalawi | All rights reserved

47
Example :: Loading Image

- In this program, we insert a command button and an image control


into the form. Besides that, we set the image Strech property to true.
- Next, enter te following code:

Private Sub cmd_LoadImg_Click()


MyImage.Picture = LoadPicture("C:\Users\admin.DESKTOP-
G1G4HEK\Documents\My Websites\vbtutor\vb6\images\uranus.jpg")
End Sub

* 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.

Copyright © learnmalawi | All rights reserved

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

Copyright © learnmalawi | All rights reserved

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

Copyright © learnmalawi | All rights reserved

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

- In this example, we want to change the background color of the form


according to the selected option.

Copyright © learnmalawi | All rights reserved

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:

Private Sub cmd_SetColor_Click()


If Option1.Value = True Then
Form1.BackColor = vbRed
ElseIf Option2.Value = True Then
Form1.BackColor = vbBlue
Else
Form1.BackColor = vbGreen
End If
End Sub

Run the program, select an option and click the "Set Background Color"
produces the output, as shown below

Copyright © learnmalawi | All rights reserved

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

- In this example, we insert six option buttons.


- It is better to make the option buttons into a control array as they
perform similar action, i.e to change shape.
- In order to create a control array, click on the first option button,
rename it as MyOption. Next, click on the option button and select
copy then paste.
Copyright © learnmalawi | All rights reserved

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

Copyright © learnmalawi | All rights reserved

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

- The DriveListBox is for displaying a list of drives available in your


computer.
Copyright © learnmalawi | All rights reserved

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

- The DirListBox means the Directory List Box.


- It is for displaying a list of directories or folders in a selected drive.
- When you place this control into the form and run the program, you
will be able to select different directories from a selected drive in your
computer as shown below

Copyright © learnmalawi | All rights reserved

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

The structure of an event procedure is as follows:

Copyright © learnmalawi | All rights reserved

60
Private Sub Command1_Click

VB Statements

End Sub

- You enter the codes in the space between Private Sub


Command1_Click............. End Sub.
- The keyword Sub actually 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 a number of 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 exactly the same, so it is fairly 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
Copyright © learnmalawi | All rights reserved

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

- This is a counter which start counting after the user click on a


command button. In this program, we insert a label, two command
buttons and a Timer control.
- The label acts as a counter, one of the command buttons is to start
the counter and the other one is to stop the counter.
- The Timer control is a control that is only used by the developer, it is
invisible during runtime and it does not allow the user to interact with
it.
- The Timer's Interval property determine how frequent the timer
changes. A value of 1 is 1 milliseconds which means a value of 1000
represents 1 second.
- In this example, we set the interval to 100, which represents 0.1
second interval. In addition, the Timer's Enabled property is set to
false at design time as we do not want the program to start counting
immediately, the program only start counting after the the user clicks
on te "Start Counting" button. You can also reset the counter using
another command button.

The Code
Dim n As Integer
Private Sub cmd_StartCount_Click()
Copyright © learnmalawi | All rights reserved

63
Timer1.Enabled = True
End Sub

Private Sub cmd_Stop_Click()


Timer1.Enabled = False
End Sub

Private Sub Command1_Click()


Lbl_Display.Caption = 0
End Sub

Private Sub Timer1_Timer()


n=n+1
Lbl_Display.Caption = n
End Sub

- We declare the variable n in the general area. After the Timer1 is


enabled, it will add 1 to the preceding number using n=n+1 after
every interval untill the user click on the "Stop Counting" button.

Copyright © learnmalawi | All rights reserved

64
The Output

Example Click and Double Click

- 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:

Private Sub MyLabel_Click()


MyLabel.Caption = "You Click Me Once"
End Sub
Private Sub MyLabel_DblClick()
MyLabel.Caption = "You Click Me Twice!"
End Sub
Copyright © learnmalawi | All rights reserved

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

Copyright © learnmalawi | All rights reserved

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 - .

i. For multiplication, we use *,


ii. for division we use /,
iii. for raising a number x to the power of n, we use x ^n and
iv. for square root, we use Sqr(x).

- VB offers many more advanced mathematical functions such as Sin,


Cos, Tan and Log,.
- There are also two important functions that are related to arithmetic
operations, i.e. the functions Val and Str$ where Val is to convert text
to a numerical value and Str$ is to convert numerical to a string
(text).
- While the function Str$ is as important as VB can display a numeric
value as string implicitly, failure to use Val will result in the wrong
calculation.

Example
Private Sub Form_Activate()
Text3.text=text1.text+text2.text
End Sub

Copyright © learnmalawi | All rights reserved

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.

Visual Basic Data Types

- VB6 classifies the information into two major data types, they are the

i. Numeric data types and the


ii. Non-numeric data types.

Numeric Data Types

- 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.

- In Visual Basic, numeric data are divided into 7 types, depending on


the range of values they can store.
- Calculations that only involve round figures can use Integer or Long
integer in the computation.
- Programs that require high precision calculation need to use Single
and Double decision data types, they are also called floating point
numbers.
- For currency calculation , you can use the currency data types.
- Lastly, if even more precision is required to perform calculations that
involve many decimal points, we can use the decimal data types.
- These data types summarized below

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

Copyright © learnmalawi | All rights reserved

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).

Non-numeric Data Types

- Nonnumeric 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 below

Copyright © learnmalawi | All rights reserved

70
Nonnumeric Data Types

Data Type Storage Range

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

Boolean 2 bytes True or False

Object 4 bytes Any embedded object

Any value as large as


Variant(numeric) 16 bytes
Double

Length+22 Same as variable-length


Variant(text)
bytes string

Suffixes for Literals

- 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

Copyright © learnmalawi | All rights reserved

71
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#

Managing Variables

- Variables are named locations in a computer program


- Variables are like mail boxes in the post office. The contents of the
variables changes every now and then, just like the mail boxes.

Copyright © learnmalawi | All rights reserved

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

• It must be less than 255 characters


• No spacing is allowed
• It must not begin with a number
• Period is not permitted
• Cannot use exclamation mark (!), or the characters @, &, $, #
• Cannot repeat names within the same level of scope.

Examples of valid and invalid variable names are displayed in Table below

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

Copyright © learnmalawi | All rights reserved

73
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.
- You can use any variable to hold any data , but different types of
variables are designed to work efficiently with different data types .
The syantax is as follows:

Dim VariableName As DataType

- If you want to declare more variables, you can declare them in


separate lines or you may also combine 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

Copyright © learnmalawi | All rights reserved

74
Dim doDate As Date
Dim password As String, yourName As String, firstnum As Integer

- Unlike other programming languages, Visual Basic actually doesn't


require you to specifically declare a variable before it's used. If a
variable isn't 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, just use the same format as example
above. However, for the fixed-length string, you have to use the
syntax as shown below:

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.

Copyright © learnmalawi | All rights reserved

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.

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, we 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.

Copyright © learnmalawi | All rights reserved

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

The syntax to declare a constant is

Constant Name As Data Type = Value

Example

- In this example, we insert a Shape control and two command buttons.


Set the shape value of the Shape control to 3 so that it becomes a
circle.
- Rename one of the command buttons to CmdResize for changing the
size of the circle. Rename the other command button as CmdArea for
calculation of the area of the circle.
- In this program, we declare four variables and a constant in the
General section.
- The varaible 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.

Copyright © learnmalawi | All rights reserved

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

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 Sub

Private Sub CmdResize_Click()


h = InputBox("Enter the value of height")
MyShape.Height = h

End Sub

Copyright © learnmalawi | All rights reserved

78
The Output

Assigning Values to Variables

- After declaring various variables using the Dim statements, we can


assign values to those variables. The syntax of an assignment is

Variable=Expression

Copyright © learnmalawi | All rights reserved

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 in Visual Basic

- Operators are symbols that are used to manipulate inputs from users
and to generate results,
- We need to use various mathematical operators

Copyright © learnmalawi | All rights reserved

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

Operator Mathematical function Example>

^ Exponential 2^4=16

* Multiplication 4*3=12,

/ Division 12/4=3

Modulus (returns the remainder from


Mod 15 Mod 4=3
an integer division)

Integer Division(discards the decimal


\ 19\4=4
places)

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

Example
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
Copyright © learnmalawi | All rights reserved

81
Label1.Caption = yourName
End Sub

- In above 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,
- the variable yourName will be assigned the data by combining the first
two variables.
- Finally, yourName is displayed on Label1.

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.

Copyright © learnmalawi | All rights reserved

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

Private Sub Command1_Click()


If userpass.Text = password Then
Label2.Visible = True
number1.Visible = True
number2.Visible = True
sum.Visible = True
Label3.Visible = True
Command3.Visible = True
usernum1.Visible = True
usernum2.Visible = True
OK.Visible = True
Label4.Visible = True
Label4.Caption = textbox1.Text
textbox1.Visible = False
userpass.Visible = False
username.Visible = False
Copyright © learnmalawi | All rights reserved

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

Private Sub OK_Click()


firstnum = usernum1.Text
secondnum = usernum2.Text
total = sum.Text
If total = firstnum + secondnum And Val(sum.Text) <> 0 Then
correct.Visible = True
wrong.Visible = False
Else
correct.Visible = False
wrong.Visible = True
End If

End Sub

Copyright © learnmalawi | All rights reserved

84
The Output

Figure 6.1 The Login dialog

Conditional Operators(Relational Operators)

- To control the VB program flow, we can use various conditional


operators.

Copyright © learnmalawi | All rights reserved

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

> More than

< Less Than

> More than or equal

<= Less than or equal

<> Not Equal to

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
below

Copyright © learnmalawi | All rights reserved

86
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

- 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

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

- To effectively control the VB program flow, we shall use


If...Then...Else statement together with the conditional operators and
logical operators.

If conditions Then

VB expressions

Else

VB expressions

Copyright © learnmalawi | All rights reserved

87
End If
Example

- This program simulates a sign in process.


- If the username and password are correct, sign in is successful else
sign in failed.
- Start VB6 and insert two textboxes on the form, rename them UsrTxt
and pwTxt, the first textbox is to accept username input and the
second one for password input.
- For pwTxt, set the PasswordChr(password characters) property to *
so that the password will appear as * instead of the actual character.
- We have written the code so that both username and password must
be correct to enable sign in if either one of them incorrect sign in will
fail.

The Code
Private Sub OK_Click()
Dim username, password As String
username = "John123"
password = "qwertyupi#@"

If UsrTxt.Text = username And pwTxt.Text = password Then


MsgBox ("Sign in sucessful")
ElseIf UsrTxt.Text <> username Or pwTxt.Text <> password Then

MsgBox ("Sign in failed")


End If
Copyright © learnmalawi | All rights reserved

88
End Sub
The Output

Example

- This example calculate 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
Copyright © learnmalawi | All rights reserved

89
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

Copyright © learnmalawi | All rights reserved

90
comm = 0
End If
LblComm.Caption = Format(comm, "$#,##0.00")
End Sub

The Output

Example : Guess a Number Game

- 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.

Copyright © learnmalawi | All rights reserved

91
The Code
'Guess a Number
Const realNumber = 99
Dim userNumber As Integer

Private Sub EXit_Click()


End
End Sub

Private Sub OK_Click()

userNumber = entry.Text
If userNumber > realNumber Then

hint.Caption = "Your number is too big"


ElseIf userNumber < realNumber Then

hint.Caption = "Your number is too small"

entry.Text = ""
entry.SetFocus
Else

Copyright © learnmalawi | All rights reserved

92
hint.Caption = "Congratulation, your number is correct"

End If

End Sub

The IIf() Function

- The IIf function denotes immediate decision function. It provides a


simple decision making process based on three arguments, as follows:

IIf(x, y, z)

x represents a logical expression while y and z represent a numeric or a


string expression.

For example, the IIF(x>y, expression 1, expression 2) function evaluates the


values of x and y, if x>y. then expression 1 is true, otherwise the expression
2 is true.

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)

ans = IIf(a < b, b - a, a * b)


MsgBox ans
End Sub

Private Sub CmdString_Click()


Dim A, B, C As String
A = InputBox("Enter a word")
B = InputBox("Enter another word")
C = IIf(A < B, A, B)
MsgBox C
End Sub

Copyright © learnmalawi | All rights reserved

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

- The Select Case control structure is slightly different from the


If....ElseIf control structure .The difference is that the Select Case

Copyright © learnmalawi | All rights reserved

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:

Select Case expression


Case value1
Block of one or more VB statements

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

Copyright © learnmalawi | All rights reserved

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

Example above can be rewritten as follows:

Dim mark As Single

Private Sub Compute_Click()


'Examination Marks
mark = mrk.Text
Select Case mark
Case 0 to 49
comment.Caption ="Need to work harder"
Case 50 to 59
comment.Caption = "Average"
Case 60 to 69
comment.Caption = "Above Average"
Copyright © learnmalawi | All rights reserved

97
Case 70 to 84
comment.Caption = "Good"
Case Else
comment.Caption ="Excellence"

End Select
End Sub

Example : Guess a Number

- In this example, we use the Select Case statement to guess a number


generated randomly. The syntax 1 + Int(6 * Rnd) generates a random
number from 1 to 6 inclusive

The Code
Dim Secret_Number As Integer

Private Sub Command1_Click()

Dim Your_Number As Integer


Your_Number = InputBox("Enter a number between 1 and 6 includisve")
Select Case Your_Number
Case Is < Secret_Number
MsgBox ("Your number is smaller than the secret number, try again!")
Case Is > Secret_Number
MsgBox ("Your number is greater than the secret number, try again!")

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

The Do Loop statements have four different forms, as shown below:

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

The above example can be rewritten as

Do
counter=counter+1
Loop until counter>1000

Exiting the Loop

Sometime we need exit to exit a loop earlier when a certain condition is


fulfilled. The keyword to use is Exit Do.

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

In the above example, we compute the summation of


1+2+3+4+……+100. In the design stage, you need to insert a ListBox into
the form for displaying the output, named List1. The program uses the
AddItem method to populate the ListBox. The statement List1.AddItem "n"
& vbTab & "sum" will display the headings in the ListBox, where it uses the
vbTab function to create a space between the headings n and sum.

The For....Next Loop

The For....Next Loop event procedure is written as follows:

For counter=startNumber to endNumber (Step increment)

One or more VB statements

Next

Copyright © learnmalawi | All rights reserved

101
Example

Private Sub Command1_Click()


Dim counter As Integer
For counter = 1 To 10
List1.AddItem counter
Next
End Sub
Example
Private Sub Command1_Click()

Dim counter As Integer


For counter = 1 To 1000 Step 10
counter = counter + 1
Print counter
Next
End Sub

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.

The While….Wend Loop

The structure of a While….Wend Loop is very similar to the Do Loop. it takes


the following form:

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

Birbal, R Taylor, M (2010). Log on to IT for CSEC. England: Carlong


Publishers Limited.

Copyright © learnmalawi | All rights reserved

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.

Langat, J Musonye, D Wanjohi, A (2006). Foundatudiesudent’k f 2 .


Nairobi: Jomo Kenyatta Foundation.

Internet

Copyright © learnmalawi | All rights reserved

105

You might also like