Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

University of Basrah

Collage of Engineering
Department of Petroleum
Computer Programming

Introduction to Visual Basic Express 2010

First Year

By

Assist Lect. Haider S. Mohammed


Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

1.1 What is visual basic 2010?

Visual Basic 2010 is the latest version of Visual Basic launched by Microsoft in 2010. Which evolved
from the earlier DOS version called BASIC. A graphical-based language allows the user to work
directly with graphics. Visual Basic is derived from the “visual” term refers to the method used to
create the graphical user interface (GUI). The “Basic” term refers to the BASIC (Beginners All-
Purpose Symbolic Instruction Code) language, a language used by more programmers.

 Getting started with Visual basic 2010

To run Visual Basic program, select:

1. Start menu >> Programs >> Microsoft Visual Studio 2010 Express >> Microsoft Visual Basic 2010
Express
2. New Project
3. Windows Forms Application
4. The main window of the program

1
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

1.2 Elements of Integrated Development Environmental (IDE).

The IDE contains several components as shown below:

Menu Bar
Tool Bar

Solution Explorer

Form Window

Toolbox

Error List Properties Window

 Menu Bar: Contains a standard command and specific command like (File, Edit, View, Project,
Format, Debug, Run, etc.).
 Tool Bar: Contains several icons that provide quick access to commonly used features.
 Error List windows: display the errors that could be occurred in the program
 Solution Explorer: The Solution Explorer contains a list of files and forms in your project. If
the Solution Explorer isn’t visible, go the View menu and select Solution Explorer to display it.
 Form1 (Form) window: contains a form named Form1, which is where the program’s Graphical
User Interface (GUI) will be displayed. A GUI is the visual portion of the program, this is where
the user enters data (called inputs) to the program and where the program displays its results
(called outputs). We refer to the Form1 window simply as “the form”. Forms are the foundation
for creating the interface of an application. You can use the forms to add windows and dialog
boxes to your application. You can also use them as containers for items that are not a visible part
of the application’s interface. For example, you might have a form in your application that serves
as a container for graphics that you plan to display in other forms.

2
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

 Toolbox controls

The Toolbox contains the controls you need to design a form. You can click on a control in the
Toolbox and drag it to the form to make it a part of the user interface. Each control in the Toolbox
has a special use, just like the tools in real toolbox. You’ll soon learn how to use some of the basic
tools in the Toolbox.

 Properties Window

The Properties window contains a list of properties for each control. When you select the form or any
control on a form, the Properties window displays the properties for that control. The column on the
left contains the names of the properties for that control. The column on the right contains the settings
for the properties. You can change these settings, and thus change your program, by clicking on the
name of the property and changing its setting on the right. Each control has its own unique set of
properties. Most controls have similar properties so be careful to select the correct control on the form
before you make changes to any properties. Table (2) explain objective of the properties window.

2 Saving and Running a Project


 To save a project, use the File - Save All menu. You can click the Save All button shown in the
figure below. This will save all files in the project. Also, you can change the name of the project
as shown below after that click save.

3
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

 There are several ways to run a project to test it.

Use the Debug menu, Start Debugging option, or Press the F5 function key to run the project, or
Click the shortcut green arrow on the shortcut toolbar.

Example 1: Design a form with one text box and two Commands button. Write a code so when run
project and click on Button1 (O.k.) display the word (Welcome) in text box, and when click on
Button2 (Close) terminate the program and return back to the form interface.

4
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Solution:

Creating the Interface: The first step in building a Visual Basic application is to create the forms
that will be the basis for your application’s interface. Then you draw the objects that make up the
interface on the forms you create.
1. Adding a text box to the form. Double-click the toolbox’s textbox to create
a text box with sizing handles in the center of the form.
2. Adding a Button1 to the form. Click on button and draw button1 to form then the button appears
on form.
3. Repeat step 2 to add a Button2 to the form.

Setting Properties
The next step is to set properties for the objects. The properties window provides an easy way to set
properties for all objects on a form. For Example1, you’ll need to change three property settings. Use
the default setting for all other properties.
Object Property Setting
Name Form1
Form1 Text Example1
Font Bold and size 12
Name Button1
Button1 Text O.k
Font Bold and size 12
Name Button 2
Button2
Text Close
Font Bold and size 12
Name Textbox1
TextBox
Text Empty
5
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Writing Code:
The code editor window is where you write Visual Basic code for your application. Code consists of
language statements, constants, and declarations. To open the code window, double-click the form or
control for which you choose to write code, or from the Project Explorer window, select the name of
a form and choose the View code button.
 In the Object list box, select the name of an object in the active form. Or double click of an
object.
 In the procedure list box, select the name of an event for the selected object. The Click
procedure is the default procedure for a command button and the Load is default procedure
for a form.
 An event procedure for a control combines the control’s actual name (specified in the name
property), an underscore ( _ ), and the event name. For example, (Button1_click).
 Type the code between the Private Sub and the End Sub statements.

Choose Button1 and type the following code:


Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
TextBox1.Text = ("welcome")
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


End
End Sub
End Class

Running the Application


To run the application, choose start from the run menu, or click the start button on the toolbar, or F5
Click button1 (O.k.) and see the “Welcome” displayed in the text box. Click button2 (close) the end
the program and return to the form window.

Example 2: Design a form shown in figure below, with three Text boxes and Button. Write code in
the Button1 (Execute). So when run project enter the Student Name in TextBox (TextBox1) and the
Father Name in TextBox (TextBox2). When click on Button1 (Execute) display the Full Name in the
TextBox (TextBox3).

6
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Solution:
Creating the Interface.:
1. Adding a Label to the form1. Double-click the Label’s Label to create a Label with sizing
handles in the center of the form1.
2. Repeat step 1 to add Label2 and Label3.
3. Adding a Textbox to the form1. Double-click the toolbox’s textbox to create a text box with
sizing handles in the center of the form1.
4. Repeat step 3 to add TextBox2 and Textbox3.
5. Adding a Button1 to the form. Click on button and draw Button to form then the Button1 appears
on form1.

7
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Setting Properties
Object Property Setting
Name Form1
Form1 Text Example2
Font Bold and size 12
Name Button1
Button1 Text Execute
Font Bold and size 12
Name Textbox1
TextBox1
Text Empty
Name Textbox2
TextBox2
Text Empty
Name Textbox3
TextBox3
Text Empty
Name Label1
Label1 Text Student name
Font Bold and size 12
Name Label1
Label2 Text Student name
Font Bold and size 12
Name Label1
Label3 Text Father name
Font Bold and size 12

Writing Code:
Private Sub Button1_Click (ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
TextBox3.Text = TextBox1.Text + " " + TextBox2.Text
End Sub

Running the Application


To run the application, choose start from the run menu, or click the start button on
the toolbar, or F5 Click the command button1 (Execute) and see the Full Name
displayed in the TextBox3.

8
University of Basrah
Collage of Engineering
Department of Petroleum
Computer Programming

Fundamentals of programming in
Visual Basic

First Year

By

Assist Lect. Haider S. Mohammed


Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

2. Fundamentals of programming in Visual Basic


2.1 Managing VB2010 Data
In our daily life we come across many types of data. For example, we need to handle data
such as names, addresses, money, dates, stock quotes, statistics and more everyday.
Similarly, in Visual Basic 2010, we have to deal with all sorts of data; some are numeric
in natrure while some are in the form of text or other forms. VB2010 divides data into
differenttypes so that it is easier to manage when we need to write the code involving those
data. Visual Basic classifies the information mentioned above into two major data types;
namelythe numeric data types and the non-numeric data types.

2.1.1 Numeric Data Types


Numeric data types are types of data that consist of numbers, which you can compute
them mathematically with various standard operators such as add, minus, multiply, divide
and so on. Examples of numeric data types are your examination marks, your height and
your weight, the number of students in a class, share values, price of goods, monthly bills,
fees and more. In Visual Basic 2010, we divide numeric data into more than five,
depending on the range of values they can store. Calculations that only involve round
figures or data that do not need precision can use Integer or Long integer in the
computation. Programs that require high precision calculation need to use Single and
Double decision data types, we also call them floating-point numbers. For currency
calculation, you can use the currency data types. Lastly, if even more precision is requires
which involve many decimalpoints, we can use the decimal data types.

1. Integer: A variable of type integer requires 2 bytes of memory and can hold the
whole numbers from -32768 to 32767.
2. Long: A variable of type Long requires 4 bytes of memory and can hold the whole
numbers from -2147483648 to 2147483647.
3. Single: A variable of type Single requires 4 bytes of memory and can hold 0, the
numbers from 1.4012923x10-45 to 3.40283x1038 with the most seven significant
digits, and the negatives of these numbers.

1
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

4. Double: A variable of type Double requires 8 bytes of memory and can hold 0, the
numbers from 4.94065x10-324 to 1.7976x10308 with at most 14 significant digits and
the negatives of these numbers.
5. Currency: The currency data type is particularly useful for calculations involving
money. A variable of type Currency requires 8 bytes of memory and can hold any
number from -9x1014 to 9x1014.

2.1.2 Non-Numeric Data Types


Nonnumeric data types are data that cannot be manipulated mathematically using
standard arithmetic operators. The non-numeric data comprises text or string data types,
the Date data types, the Boolean data types that store only two values (true or false),
Object data type and Variant data type.

1. Boolean: A variable of type Boolean requires 2 bits of memory and holds either the
value True or False. If boolVar is a Boolean variable, then the statement Print
boolVar displays (1) when the value is True and displays (0) when the value is False.
2. Date: A variable of type Date requires 8 bytes of memory and holds numbers
representing dates from January 1St 100 To December 31St 9999. Values of dateVar
are displayed in the form month/day/year (for example, 5/12/1996).
3. String: A variable of type string requires 1 byte of memory per character and can
hold a string of up to 32,767 characters, string values are enclosed in quotes.
4. Variant: A variable of type variant can be assigned numbers, Strings and several
other types of data. A variable of type variant requires 16 bytes of memory and can
hold any type of data. When values are assigned to a variant variable, Visual Basic
keeps track of the "type" of data that has been sorted. By default, Visual Basic uses
the variant data type.

2
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

2.2 Variables
Variables are like mail boxes in the post office. The contents of the variables changes
every now and then, just like the mail boxes. In term of VB2010, 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 2010, you have to follow a
set of rules.

Variable Names

The following are the rules when naming the variables in Visual Basic 2010

 It must be less than 255 characters


 No spacing is allowed
 It must not begin with a number
 They can’t be the same as restricted keywords (a restricted keyword is a word that
Visual Basic uses as part of its language. This includes predefined statements such
as “If and Loop”, functions such as “Len and Abs”, and operators such as “Or and
Mod”).

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

Valid Name Invalid Name


My_Car My.Car
ThisYear 1NewBoy
Long_Name_Can_beUSE He&HisFather *& is not acceptable
Table 2: Valid and Invalid Names

2.2.1 Declaring Variables

In Visual Basic 2010, one needs to declare the variables before using them by assigning
names and data types. If you fail to do so, the program will show an error. They are
normally declared in the general section of the codes' windows using the Dim statement.

The format is as follows:

Dim Variable Name As Data Type

3
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Example 2.1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load

Dim password As String

Dim yourName As String

Dim firstnum As Integer

Dim secondnum As Integer

Dim total As Integer

Dim doDate As Date

End Sub

 You may also combine them in one line, separating each variable with a comma, as
follows:

Dim password As String, yourName As String, firstnum As Integer,.............

2.3 Constants

Constants are different from variables in the sense that their values do not change
during the running of the program.

2.3.1 Declaring a Constant

The format to declare a constant is

Const Constant Name As Data Type = Value

4
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Example 2.3

Private Sub Form1_Load (ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles MyBase.Load

Const Pi As Single=3.142

Const Temp As Integer =37

Const Score As Integer =100

End Sub

2.4 Assignment Statement


(Variable-Name=Expression): Expression may include constant, character, variable
(or variables), operators and functions. For example
City=”Baghdad”
Age=29
X=2*X
Z= A+B
m= Sin (d)

Suffix for Literals


Literals are values that you assign to a data. In some cases, we need to add a suffix
behind a literal so that VB2010 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 1.

Suffix Data Type Examples


% integer Dim A%
& Long Dim A&
! Single Dim A!
# Double Dim A#
@ Currency Dim A@
$ String Dim A$
6
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

3. Visual Basic Operators

1. The simplest operators carry out arithmetic operations. These operations in their
order of precedence are:

Operation Code Operation


^ Exponent
*, / Multiplication and division
\ Integer division
Mod Modulus-rest of division
-,+ Subtraction and addition

2. To Concatenate two strings, use the & symbol or the + symbol


3. There are six Comparison operators in Visual Basic.

Operation Code Comparison


> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
= Equal to
< > or > < Not equal to

4. There are three logical operators:

Operation Code Operation


Not Logical not
And Logical and
Or Logical or

Note: Logical operators follow arithmetic operators in precedence.

7
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Examples:

Public Class Form1

Private Sub Button1


Label1.Text = 3 / 2

Label2.Text = 3 \ 2

Label3.Text = 3 Mod 2

Label4.Text = 3 * 2

Label5.Text = 3 + 2

Label6.Text = 3 - 2

Label7.Text = 3 \ 2 * 4

Label8.Text = 3 * 2 \ 4

Label9.Text = (3 / 2) * 2

Label10.Text = 3 * 2 ^ 2

End Sub

End Class

8
University of Basrah
Collage of Engineering
Department of Petroleum
Computer Programming

Lecture Four
Control Structures

First Year

By

Assist Lect. Haider S. Mohammed


Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

4. Control Structures

In this chapter, you will learn how to write Visual Basic code that can make
decision when it process input from the users, and control the program flow in
the process. Decision making process is an important part of programming
because it will help solve practical problems intelligently so that it can provide
useful output or feedback to the user. For example, we can write a Visual Basic
program that can ask the computer to perform certain task until a certain condition
is met, or a program that will reject non-numeric data. In order to control the
program flow and to make decisions, we need to use the conditional operators
and the logical operators together with the If control structure. To effectively
control the Visual Basic program flow, we shall use the If control structure
together with the conditional operators and logical operators. There are basically
three types of If control structures, namely:

• If ...Then
• If – Then –Else
• Select Case

4.1 If ... Then Statement:


This is the simplest control structure which ask the computer to perform a certain
action specified by the Visual Basic expression if the condition is true. However,
when the condition is false, no action will be performed. The general format for
the (If- Then) statement is

4.1-1 If Condition Then Statement


Where, Condition is usually a comparison, but it can be any expression that
evaluates to a numeric value, this value as true or false. If condition is True,
Visual Basic executes all the statements following the Then keyword.

1
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Example 4-1: Write a program to enter the value of two variables (X and Y).
Find and print the maximum value for two variables. Design form window and
select all the control objects are used.

Solution
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim x, y, max As Integer
x = Val(TextBox1.Text)
y = Val(TextBox2.Text)
max = x
If y > x Then max = y
TextBox3.Text = CStr(max)
End Sub
End Class

4.1-2 If condition Then Goto n Where n : number of statement ( must be Positive


Integer value) for example: Goto 5 , Goto 16 , Goto 2010

2
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Example 4.2: Used (If-Then Goto) condition to write a program for the
previous Example 4.1

Solution:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim x, y, max As Integer
x = Val(TextBox1.Text)
y = Val(TextBox2.Text)
If y > x Then max = y : GoTo 10
max = x
10: TextBox3.Text = CStr(max)
End Sub
End Class

Note: The statement Exit Sub used to stop the program without return to the
project window.

3
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

4.2 If - Block Statement:


4.2.1 (If – Then – EndIf) statement: The If...Then – EndIf Statement performs
an indicated action only when the condition is True; otherwise the action is
skipped.
If condition Then
VB Expression
End If
Example 4.3: Used (If – Then – EndIf) condition to write a program for the
previous Example 4.1
Solution
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim x, y, max As Integer
x = Val(TextBox1.Text)
y = Val(TextBox2.Text)
max = x
If y > x Then
max = y
End If
TextBox3.Text = CStr(max)
End Sub
End Class

4
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

4.2.2 (If – Then – Else) statement: The If – Then - Else statement allows the
programmer to specify that a different action is to be performed when a certain
action specified by the VB expression if the condition is True than when the
condition is false, an alternative action will be executed. The general format for
the If - Then - Else statement is
If condition Then
VB expression
Else
VB expression
End If
Example 4.4: Used (If – Then – Else) condition to write a program for the
previous Example 4.1
Solution
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim x, y, max As Integer
x = Val(TextBox1.Text)
y = Val(TextBox2.Text)
If y > x Then
max = y
Else
max = x
End If
TextBox3.Text = CStr(max)
End Sub
End Class

5
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

4.2.3 Nested (If – Then – Else) statement: If there are more than two alternative
choices, using just If – Then - Else statement will not be enough. In order to
provide more choices, we can use If...Then... Else statement inside If...Then...Else
structures. The general format for the Nested If...Then…Else statement is

Example 4.5: Write a program to enter the value of variable (Mark). Find the
grade using If – Block statement and display the value of grade in a text box.
When the value of variable (Mark) exceed 100, write a Message Box (Wrong
entry, please Re-enter the Mark). Design form window and select all the control
objects are used.

6
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Solution:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim Mark As Single, Grade As String
Mark = Val(TextBox1.Text)
If Mark > 100 Then
MessageBox.Show("Wrong entry, Re-enter the Mark")
TextBox1.Text = "" : TextBox2.Text = "" : Exit Sub
ElseIf Mark >= 90 Then
Grade = "Excellent"
ElseIf Mark >= 80 Then
Grade = "Very Good"
ElseIf Mark >= 70 Then
Grade = "Good"
ElseIf Mark >= 60 Then
Grade = "Medium"
ElseIf Mark >= 50 Then
Grade = "Pass"
Else : Grade = "Fail"
End If
TextBox2.Text = (Grade)
End Sub

4.3 Select- Case statement: Select - Case structure is an alternative to If –


Then - ElseIf for selectively executing a single block of statements from among
multiple block of statements. The Select Case control structure is slightly
different from the If - ElseIf control structure. The difference is that the Select
Case control structure basically only makes decision on one expression or

7
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

dimension while the If – ElseIf statement control structure may evaluate only one
expression, each If – ElseIf statement may also compute entirely different
dimensions. Select- Case is more convenient to use than the If- Else - End If. The
format of the Select Case control structure is as follows:

Select Case test expression


Case expression list 1
VB statements
Case expression list 2
VB Statements
Case expression list 3
VB statements
Case expression list 4

Case Else
VB Statements
End Select

Example 4.6: Example 4.5 can be rewritten as follows:

8
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Solution 1
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim Mark As Integer, Grade As String
Mark = Val(TextBox1.Text)
Select Case Mark
Case 0 To 49
Grade = "Fail"
Case 50 To 59
Grade = "pass"
Case 60 To 69
Grade = "medium"
Case 70 To 79
Grade = "good"
Case 80 To 89
Grade = "very good"
Case 90 To 100
Grade = "excellent"
Case Else
MessageBox.Show("wrong entry, please re-enter the mark")
TextBox1.Text = ""
TextBox2.Text = ""
Exit Sub
End Select
TextBox2.Text = Grade
End Sub
End Class

9
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Solution 2
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim Mark As Integer, Grade As String
Mark = Val(TextBox1.Text)
Select Case Mark
Case Is > 100, Is < 0
MessageBox.Show("wrong entry, please re-enter the mark")
TextBox1.Text = "" : TextBox2.Text = "" : Exit Sub
Case Is >= 90
Grade = "excellent"
Case Is >= 80
Grade = "very good"
Case Is >= 70
Grade = "good"
Case Is >= 60
Grade = "medium"
Case Is >= 50
Grade = "pass"
Case Is <= 49
Grade = "fail"
End Select
TextBox2.Text = (Grade)
End Sub
End Class

10
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

H.W
1. Write a program to enter a user name and display the message (hello) three
times. The first one for (Mena), the second one for (Nastia) and the third for any
user as a guest.

2. Design a form with four TextBoxes and three Buttons. Design the program so
that the values of num1, num2, and Symbol are entered into separate three text
boxes. Write a code to perform (add, subtract, multiply and divide) when pressing
on Button (Calculate). Display the result in separate text box. The Button (Clear)
used to clear values in TextBoxes. Click Button (Exit) to end the program and
return to the project window.

11
University of Basrah
Collage of Engineering
Department of Petroleum
Computer Programming

Lecture Five
Loops (Repetition) Structures

First Year

By

Assist Lect. Haider S. Mohammed


Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

5. Loops (Repetition) Structures


Visual Basic allows a procedure to be repeated as many times as long as the
processor and memory could support. This is generally called looping. Looping
is required when we need to process something repetitively until a certain
condition is met. In Visual Basic, we have three types of Loops, they are
• For...Next loop,
• Do loop

5-1 For...Next Loop


The format is:
For counter = Start To End Step [Increment]
One or more VB statements
Next [counter]

The arguments counter, start, end, and increment are all numeric. The increment
argument can be either positive or negative. If increment is positive, start must be
less than or equal to end or the statements in the loop will not execute. If
increment is negative, start must be greater than or equal to end for the body of
the loop to execute. If steps isn’t set, then increment defaults to 1.
In executing the For loop, visual basic:
1. Sets counter equal to start.
2. Tests to see if counter is greater than end. If so, visual basic exits the loop (if
increment is negative, visual basic tests to see if counter is less than end).
3. Executes the statements.
4. Increments counter by 1 or by increment, if it’s specified.
5. Repeats steps 2 through 4.

1
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

For Example:
1- For I=0 To 10 step 5
Statements
Next I
2- For counter = 100 To 0 Step -5
Statements
Next counter

Example 5-1: Design a form and write code to find the summation of numbers
(from 0 to 100) using For Next Loop.

Solution
Public Class Form1
Private Sub Button1_Click ( )
Dim i, Total As Integer
Total = 0
For i = 0 To 100
Total = Total + i
Next i
MessageBox.Show("Total=" +
CStr(Total))
End Sub
End Class

2
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Example 5-2: Design a form and write code to find the summation of even
numbers (from 0 to 100) using For Next Loop.

Solution:
Private Sub Button1_Click ( )
Dim i, Total As Integer
Total = 0
For i = 0 To 100 Step 2
Total = Total + i
Next i
TextBox1.Text = CStr (Total)
End Sub

Example 5-3: Design a form and write code to find the summation of odd
numbers (from 0 to 100) using For Next Loop.
Solution:
Private Sub Button1_Click ( )
Dim i, Total As Integer
Total = 0
For i = 0 To 100
If i Mod 2 = 1 Then Total = Total + i
Next i
Label1.Text = CStr (Total)
End Sub

3
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

5-2 Do –Loop
Use a Do loop to execute a block of statements and indefinite number of times.
There are several variations of Do…Loop statement, but each evaluates a numeric
condition to determine whether to continue execution. In the following
Do…Loop, the statements execute as long as the condition is True.

5-2-1 Do While ...Loop


The formats are
Do While condition
Block of one or more VB Statement
Loop

When Visual Basic executes this Do...Loop, it first tests condition. If condition is
False, it skips past all the statements. If it’s True, Visual Basic executes the
statements and then goes back to the Do while statement and tests the condition
again. Consequently, the loop can execute any number of times, as long as
condition is True. The statements never execute if initially False.

Example 5-4: Design a form and write code to find the summation of numbers
(from 0 to N) using Do While Loop.
Solution
Private Sub Button1_Click ( )
Dim i, N, Total As Integer
Total = 0
N = Val(TextBox1.Text)
i=0
Do While i <= N
Total = Total + i
i=i+1
Loop
TextBox2.Text = CStr(Total)
End Sub
4
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

5-2-2 Do…Loop While:


Another variation of the Do...Loop statement executes the statements first and
then tests condition after each execution. This variation guarantees at least one
execution of statements.
The formats are:
Do
Block of one or more VB Statement
Loop condition

Example 5-5: Design a form and write code to find the summation of
numbers (from 0 to N) using Do Loop While.
Solution

Private Sub Button1_Click ( )


Dim i, N, Total As Integer
Total = 0
N = Val(TextBox1.Text)
i=0
Do
Total = Total + i
i=i+1
Loop While i <= N
TextBox2.Text = CStr(Total)
End Sub

5
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

5-2-3 Do Until ...Loop


Unlike the Do While...Loop repetition structures, the Do Until... Loop structure
tests a condition for falsity. Statements in the body of a Do Until...Loop are
executed repeatedly as long as the loop-continuation test evaluates to False.

The formats are


Do Until condition
Block of one or more VB Statement
Loop

Example 5-6: Design a form and write code to find the summation of numbers
(from 0 to N) using Do Until Loop.
Solution

Private Sub Button1_Click ( )


Dim i, N, Total As Integer
Total = 0
N = Val(TextBox1.Text)
i=0
Do Until i > N
Total = Total + i
i=i+1
Loop
TextBox2.Text = CStr(Total)
End Sub

6
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

5-2-4 Do… Loop Until

The formats are:


Do
Block of one or more VB Statement
Loop Until condition

Example 5-7: Design a form and write code to find the summation of numbers
(from 0 to N) using Do Loop Until.
Solution

Private Sub Button1_Click ( )


Dim i, N, Total As Integer
Total = 0
i=0
N = Val(TextBox1.Text)
Do
Total = Total + i
i=i+1
Loop Until i > N
TextBox2.Text = CStr(Total)
End Sub

7
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

5-3 Exiting Loop

The exit statement allows you to exit directly from For Loop and Do Loop, Exit
For can appear as many times as needed inside a For loop, and Exit Do can appear
as many times as needed inside a Do loop (the Exit Do statement works with all
version of the Do Loop syntax). 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 or Exit Do To exit a Do… Loop, and you can
place the Exit For or Exit Do statement within the loop; and it is normally used
together with the If...Then...statement.

Exit For Exit Do

The formats are: The formats are:


For counter= start To end step (increment) Do While condition
Statements Statements
Exit for Exit Do
Statement Statements
Next counter Loop

Example 5-8: Design a form and write code to print numbers (from 1 to 10) on
listBox using For Next statement and stop printing at number 6 using Exit For.

Solution

8
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Private Sub Button1_Click ( )


Dim i As Integer
For i = 1 To 10
If i > 6 Then Exit For
ListBox1.Items.Add(i)
Next i
End Sub

Example 5-9: Design a form and write code to print numbers (from 0 to 10) on
listBox using Do While statement and stop printing at number 5 using Exit Do.
Solution
Private Sub Button1_Click()
Dim x As Integer
x=0
Do While x < 10
ListBox1.Items.Add(x)
x=x+1
If x = 5 Then
ListBox1.Items.Add("The program is
exited at x=5")
Exit Do
End If
Loop
End Sub

9
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

5-4 Nested Loop


The nested loops are the loops that are placed inside each other. The most inner
loop will be executed first, then the outer ones. These are examples of the
nested loops.
Possible Error (Not Possible)
For I=1 to 5 For I=1 to 5
Statement Statement
For J=1 to 5 For J=1 to 5
Statement Statement
Next J Next I
Statement Statement
Next I Next J

Example 5-10: Write VB program to print the following figure. Print the figure
in TextBox.
*
**
***
****
Solution
Private Sub Button1_Click ( )
Dim i, j As Integer
For i = 1 To 4
For j = 1 To i
TextBox1.AppendText(("*" & " "))

Next j
TextBox1.AppendText(vbNewLine)
Next i
End Sub

10
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Example 5-11: Create a Visual Basic Project to find the value of the following
series.

Write the code program so that the value of constants (a, and b) are entered into
text boxes. When the users click checkbox, calculate the value of series (where
the total number of terms is equal 20). When the user unchecked the checkbox,
the number of terms (N) is entered into input box and calculate the value of series.
Display the value of series (Sum) in a separate text box.

Solution
Private Sub Button1_Click ( )
Dim a, b, Sum, N As Integer
a = Val(TextBox1.Text)
b = Val(TextBox2.Text)
Sum = b
If CheckBox1.Checked = True Then
For I = 1 To 20
Sum = Sum + a * I
Next
Else
N = Val (InputBox ("No. of terms="))
For I = 1 To N
Sum = Sum + a * I
Next
End If
TextBox3.Text = CStr(Sum)
End Sub

11
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

H.W
1. Write a program to generate the numbers from 0 to N, display the result using
List Box.
2. Write a program to generate the numbers from 0 to N, and increase the counter
10 each time, then display the result using List Box.
3. Write a program to print even numbers from 1 to N using do while loop.
4. Write a program to find the summation of the numbers from 5 to 15.
5. Write a program to print multipliers of 5 (from 5 to N).

12
Example : Create a Visual Basic Project to find the value of the following series.

Write the code program so that the number of terms (N) is entered into TextBox.
Display the result (Pi) in separate text box when click on Button (Find Pi).
Solution
Public Class Form1
Private Sub Button1_Click()
Dim S, N, I, T, Pi As Double
N = Val(TextBox1.Text)
S=0
For I = 1 To N
T=1/I^2
S=S+T
Next
Pi = Math.Sqrt(S * 6)
TextBox2.Text = CStr(Pi)
End Sub
End Class
Q1\ Write a program to generate the numbers following

(0, 1, 2, 3, 4, 25, 36, 49, 64, 81,100) on ListBox.

Solution

Private Sub Button1_Click()


Dim x, i As Integer
x=0
For i = 0 To 10
If i < 5 Then
x=i
Else
x=i^2
End If
ListBox1.Items.Add(x)
Next
End Sub
Q2\ Write a program to generate the numbers following

(2, 4, 6, 8, 10, 12, 13, 14, 16, 17) on ListBox.


Solution
Private Sub Button1_Click()
Dim x As Integer
For x = 2 To 16
If x Mod 2 = 0 Then
ListBox1.Items.Add(x)
End If
If x = 12 Then ListBox1.Items.Add(x + 1)
If x = 16 Then ListBox1.Items.Add(x + 1)
Next
End Sub
Q3\ Write a program to generate the numbers following

(1, 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61, 66, 71) on ListBox.
Solution
Private Sub Button1_Click()
Dim x As Integer
For x = 1 To 71 Step 5
ListBox1.Items.Add(x)
Next
End If
Next
End Sub
Q4\ Write a program to generate the numbers following

(1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21) on TextBox.


Solution
Private Sub Button1_Click()
Dim x As Integer
X=1
Do While x >= 21
TextBox1.AppendText(x)
TextBox1.AppendText(vbNewLine)
X=X+2
Loop
End Sub
Q5\ Write a program to generate the numbers following

(0, 5, 10, 15, 17.5, 20, 25, 27.5, 30) on ListBox.


Solution
Private Sub Button1_Click()
Dim i As Single
For i = 0 To 30 Step 5
ListBox1.Items.Add(i)
If i = 15 Then ListBox1.Items.Add(i + 2.5)
If i = 25 Then ListBox1.Items.Add(i + 2.5)
Next
End Sub
Q6\ Write a program to generate the numbers following

(29, 26, 23, 20, 17, 14, 11, 8, 5) on TextBox.


Solution
Private Sub Button1_Click()
Dim i As Integer
For i = 29 To 5 Step -5
TextBox1.AppendText(i)
TextBox1.AppendText(vbNewLine)

Next
End Sub
University of Basrah
Collage of Engineering
Department of Petroleum
Computer Programming

Lecture Six
Functions

First Year

By

Assist Lect. Haider S. Mohammed


Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

6. Functions of Visual Basic


A function is a set of commands code that performs a specific action, where they
are combined under a certain name, and when you call this name has executed
these orders. There are two types of functions, the built-in functions (or internal
functions) and the functions created by the programmers.

6.1 Built-in Functions

Visual Basic offers a rich assortment of built-in functions. The numeric and string
variables are the most common used variables in programming. Therefore, Visual
Basic provides the user with many functions to be used with a variable to perform
certain operations or type conversion. Detailed description of the function in
general will be discussed in the following functions section. The most common
functions for (numeric or string) variable X are stated in the following table.

6.1.1 Mathematical Function

Function Description
Y= Math.Abs(X) Absolute of X, |X|
Y= Math.Sqrt(X) Square root of X , √𝑋
Y= Math.Sign (X) (-1 or 0 or 1) for (X<0 or X=0 or X>0)
Y= Math.Exp (X) ex
Y= Math.Log (X) Natural logarithms, ln𝑋
Y= Math.Log(X)/ Math.Log (10) Log𝑋

Y= Math.Sin (𝑋)
Y= Math.Cos (𝑋) Trigonometric functions
Y= Math.Tan (𝑋)
Y= Math.ASin (𝑋) Inverse Trigonometric functions
Y= Math.ACos (𝑋)
Y= tan−1(𝑋) (Where X angle in radian).
Y= Math.ATan (𝑋)
Y= Int(X) Integer of X
Y= Fix(X) Take the integer part

1
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Ex 6-1:
*Private Sub Button1_Click()
Dim num1, num2 As Integer
num1 = Val(TextBox1.Text)
num2 = Math.Abs(num1)
Label1.Text = num2
End Sub
*Private Sub Button2_Click()
Dim num1, num2 As Single
num1 = Val(TextBox2.Text)
num2 = Math.Exp(num1)
Label2.Text = num2
End Sub
*Private Sub Button3_Click()
Dim num1, num2 As Single
num1 = Val(TextBox3.Text)
num2 = Fix(num1)
Label3.Text = num2
End Sub
*Private Sub Button4_Click()
Dim num1, num2 As Single
num1 = Val(TextBox4.Text)
num2 = Math.Log(num1)
Label4.Text = num2
End Sub
*Private Sub Button5_Click()
Dim num1, num2 As Single
num1 = Val(TextBox5.Text)
num2 = Int(num1)
Label5.Text = num2
End Sub

2
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

6.1.2 String Functions


Y=Len(X) Number of characters of Variable
Y=LCase (X) Change to small letters
Y=UCase (X) Change to capital letters
Y=Left (X,L) Take L character from left
Y=Right (X,L) Take L character from right
Y=Mid (X,S,L) Take only characters between S and R

Examples:
Private Sub Button1_Click()
Dim A, B, C, D, M, L, H As String
H= My Name Is
A = LCase(H)
B = UCase(H)
C = Mid(H, 3, 5)
D = LSet(H, 7)
M = RSet(H, 4)
L = Len(A)
TextBox1.Text = A
TextBox2.Text = B
TextBox3.Text = C
TextBox4.Text = D
TextBox5.Text = M
TextBox6.Text = L
End Sub

3
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Ex 6-2: Design a visual basic program with two textboxes. One is used to enter
any string and the other is used to display the inverse of this string.
Private Sub Button1_Click()
Dim x As String
Dim i, y As Integer
x = TextBox1.Text
y = Len(x)
For i = y To 1 Step -1
TextBox2.Text &= Mid (x, i, 1)
Next
End Sub

6.1.3 Converting Functions

Visual Basic provides several conversion functions can used to convert values
into a specific data type. The following table describes the convert function.

Function Description
The function CDbl converts, integer, long integer, and single
precision numbers to double-precision numbers. If x is any
CDbl
number, then the value of CDbl(x) is the double-precision number
determined by x.
The function CInt converts long integer, single-precision, and
double precision numbers to integer numbers. If x is any number,
CInt
the value of CInt(x) is the (possibly rounded) integer constant that
x determines.
The function CLng converts integer, single precision and double-
precision numbers to long integer numbers. If x is any number,
CLng
thevalue of CLng(x) is the (possibly rounded) long integer that x
determines.
The function CSng converts integer, long integer, and double-
precision numbers to single-precision numbers. If x is any number,
CSng
the value of CSng(x) is the single-precision number that x
determines.

4
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

The function CStr converts integer, long integer, single-precision,


double-precision, and variant numbers to strings. If x is any
CStr number, the value of CStr(x) is the string determined by x. unlike
the Str function, CStr does not place a space in front of positive
numbers.[variant]
The Val function is used to convert string to double-precision
Val
numbers.

6.1.4 MsgBox Function

The objective of MsgBox is to produce a pop-up message box and prompt the user
to click on a command button before he /she can continues. This format is as
follows:

Variable Name=MsgBox(Prompt, Style Value, Title)

The first argument, Prompt, displays the message in the message box. The Style
Value determines the type of command buttons appear on the message box, as
shown in Table 10.1. The Title argument will display the title of the message
board.

Table 10.1: Style Values

Style Value Named Constant Buttons Displayed


0 vbOkOnly Ok button
1 vbOkCancel Ok and Cancel buttons
2 vbAbortRetryIgnore Abort, Retry and Ignore buttons.
3 vbYesNoCancel Yes, No and Cancel buttons
4 vbYesNo Yes and No buttons
5 vbRetryCancel Retry and Cancel buttons

5
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

yourMsg is a variable that holds values that are returned by the MsgBox ( )
function. The type of buttons being clicked by the users determines the values. It
has to be declared as Integer data type in the procedure or in the general
declaration section. Table 10.2 shows the values, the corresponding named
constant and buttons.

Table 10.2: Return Values and Command Buttons

Value Named Constant Named Constant Button Clicked


1 MsgBoxResult.Ok vbOk Ok button
2 MsgBoxResult.Cancel vbCancel Cancel button
3 MsgBoxResult.Abort vbAbort Abort button
4 MsgBoxResult.Retry vbRetry Retry button
5 MsgBoxResult.Ignore vbIgnore Ignore button
6 MsgBoxResult.Yes vbYes Yes button
7 MsgBoxResult.No vbNo No button

Ex 6-3:

Private Sub Button1_Click()


Dim testmsg As Integer
testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then
MessageBox.Show("You have clicked the OK button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub

6
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

To make the message box looks more sophisticated, you can add an icon besides
the message. There are four types of icons available in VB2010 as shown in Table
10.3

Table 10.3: Named Constants and Icons


Value Named Constant Icon

16 vbCritical

32 vbQuestion

48 vbExclamation

64 vbInformation

7
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Ex 6-4

Private Sub Button1_Click()


Dim testMsg As Integer
testMsg = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "Test
Message")
If testMsg = 6 Then
MessageBox.Show("You have clicked the yes button")
ElseIf testMsg = 7 Then
MessageBox.Show("You have clicked the NO button")
Else
MessageBox.Show("You have clicked the Cancel button")
End If
End Sub

6.1.5 The InputBox Function

An InputBox function allows the user to enter a value or a message in a text box.

Variable Name =InputBox (Prompt, Title, default_text, x-position, y-position)

8
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

userMsg is a variant data type but typically it is declared as string, which


accepts themessage input by the user. The meanings of the arguments:
 Prompt - The message displayed normally as a question asked.

 Title - The title of the Input Box.


• default-text - The default text that appears in the input field where the user
maychange the message according to his or her wish.
 x-position and y-position - the position or the coordinates of the input box.

Ex 6-5:
Private Sub Button1_Click()
Dim userMsg As String
userMsg = InputBox("What is your message?", "Message Entry Form", "Enter
your messge here", 500, 700)
If userMsg <> "" Then
MessageBox.Show("userMsg")
Else
MessageBox.Show("No Message")
End If

9
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

6.2 Creating User-Defined Functions (Sub Procedure and


Function Procedure)
Most computer programs that solve real-world problems are much larger than
those presented in the first few chapters. Experience has shown that the best way
to develop and maintain a large program is to construct it from smaller pieces
each of which is more manageable than the original program. This technique is
called divide and conquer. This chapter describes many key features that facilitate
the design, implementation, operation and maintenance of large programs.

Functions and Subroutines are programs designed for specific task, and could
be called from the main program or from sub-procedures without pre definition
or declaration. Users are allowed to call in any number of times which save the
main program space, since it avoids reputation of code these subroutines could
be designed by user or could be previously built.

function procedures and sub procedures share the same characteristics, with
one important difference- function procedures return a value (i. g., give a value
back) to the caller, whereas sub procedures do not.

6.2.1 declaration syntax

 Function Procedures

Public Function Name (ByVal Variabl1 As datatype) As datatype


Statements
Return Value
End Function

10
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Public Function Name (ByVal Variabl1 As datatype, ByVal Variabl2 As


datatype) As datatype
Statements
Return Value
End Function

Call statement

X= Name (Value1)

 Sub Procedures

Public Sub Name (ByVal Variabl1 As datatype)


Statements
End Sub

Public Sub Name (ByVal Variabl1 As datatype, ByVal Variabl2 As datatype)


Statements
End Sub

Call statement

Call Name (Value1, Value2, Value3, ….)

11
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Ex 6-6: Create a program that calculates the cube root of a number, by using
function.

Public Class Form1


Public Function cubeRoot (ByVal myNumber As Single) As Single
Return myNumber ^ (1 / 3)
End Function
Private Sub Button1_Click()
Label3.Text = cubeRoot(Val(TextBox1.Text))
End Sub
End Class

Ex 6-7: BMI calculator

This BMI calculator is a Visual Basic 2010 program that can calculate the body
mass index of a person based on his or her body weight in kilogram and the body
height in meter. BMI can be calculated using the formula weight/ (height )2,
where weight is measured in kg and height in meter.

12
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

If the BMI is more than 30, a person is considered obese. You can refer to the
following range of BMI values for your weight status.

 Underweight = <18.5
 Normal weight = 18.5-24.9
 Overweight = 25-29.9
 Obesity = BMI of 30 or greater

Solution
Public Class Form1
Public Function BMI (ByVal height, ByVal weight)
Return (weight) / (height ^ 2)
End Function

Private Sub Button1_Click()


Label4.Text = Format (BMI(TextBox1.Text, TextBox2.Text), "0.00")
End Sub
End Class

13
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Ex 6-8: Future Value Calculator


In this example, the user can calculate the future value of a certain amount of
money he has today based on the interest rate and the number of years from now,
supposing he or she will invest this amount of money somewhere. The calculation
is based on the compound interest rate. This reflects the time value of money.
Future value is calculated based on the following formula:

The function to calculate the future value involves three parameters namely the
present value (PV), the interest rate (i) and the length of period (n).
Solution

Public Class Form1


Public Function FV (ByVal PV As Single, ByVal i As Single, ByVal n As
Integer) As Double
Return PV * (1 + i / 100) ^ n
End Function

Private Sub Button1_Click()


Label5.Text = FV(TextBox1.Text, TextBox2.Text, TextBox3.Text).ToString
("c")
End Sub
End Class

14
Computer Programming / VB2010 Assist Lect. Haider S. Mohammed

Ex 6-9: Write a code program to read three integer numbers. Using a define sub
procedure (Minimum) to determine the smallest of three integers. Display the
smallest value in TextBox.
Solution

Public Class Form1


Sub Minimum (ByVal n1 As Integer, ByVal n2 As Integer, ByVal n3 As
Integer)
Dim min As Integer
n1 = Val(TextBox1.Text)
n2 = Val(TextBox2.Text)
n3 = Val(TextBox3.Text)
min = n1
If n2 < min Then min = n2
If n3 < min Then min = n3
TextBox4.Text = CStr (min)
End Sub

* Private Sub Button1_Click()


Dim n1, n2, n3 As Integer
Minimum (n1, n2, n3)
End Sub
End Class
Or

* Private Sub Button1_Click ()


Minimum (TextBox1.Text, TextBox2.Text, TextBox3.Text)
End Sub

15

You might also like