VB 3 Visual Basic Looping
VB 3 Visual Basic Looping
Data File
& Error Handling
Module 3
Visual Basic Looping
• Used for operations that are repeated for some
number of times.
• Looping statements:
– Do loop variations
• do while, do until, do loop while, do loop until
– For loop
– While loop
Loops Constructs
• Pretest Loops:
Do While (or Until) condition
body of the loop
Loop
• Posttest Loops:
Do
body of the loop
Loop While (or Until) condition
Pre-Test Structures
Do While - Loop
Do Until – Loop
While – End While
For - Next
Post-Test Structures
Do - Loop While
Do - Loop Until
• Do While - Loop Structure
<Initialization statement>
Do While <condition - TRUE>
:
: < write TRUE statements here…>
[ Exit Do ]
Loop
X=1 X=1
Do While X <= 5 Do
Msgbox (“Number ” & X) Msgbox (“Number ” & X)
X=X+1 X=X+1
Loop Loop While X <= 5
X=1 X=1
Do Until X > 5 Do
Msgbox (“Number ” & X) Msgbox (“Number ” & X)
X=X+1 X=X+1
Loop Loop Until X > 5
Exercise #1
• Display sequence of numbers from 1 to 5 using
Msgbox()
X=1
While X <= 5
Msgbox (“Number ” & X)
X=X+1
End While
For X = 1 to 5
Msgbox (“Number ” & X)
Next X
Exercise #2
• Display sequence of numbers from 10 to 25
Do While - Loop Do – Loop While
X = 10 X = 10
Do While X <= 25 Do
Msgbox(X) Msgbox(X)
X=X+1 X=X+1
Loop Loop While X <= 25
End Sub
Your turn…
Write codes that print the degrees Celsius from 5
to 45 (step 5) with their equivalent degrees
Fahrenheit as follows: (Use List box)
Celsius Fahrenheit
5 41.00
10 50.00
15 59.00
20 68.00
25 77.00
30 86.00
35 95.00
40 104.00
45 113.00
Exercise #5
• The bank charges 12% simple interest on the amount
per annum. Write a VB program that allows the user
to input for the amount loan and the number of years
to pay. Compute and display the lump sum amount
for each year.
Formula: Amt = P (1 + r t)
where: Amt – lump sum amount
P – Principal amount
r – interest rate (12%)
t – # of years
Solution
Private Sub Compute_Click()
Dim Amt, P As Single, t As Integer
Const r as Single = 0.12
P = TextBox1.Text
LB.Items.Add(“Year" & vbTab & “Amount/Year")
t=1
Do While t <= Textbox2.Text
Amt = P * ( 1 + r * t)
LB.Items.Add(t & vbTab & Amt)
t=t+1
Loop
End Sub
Exercise #6
• A bank offers a car loan at the rate of 15% compounded
monthly. Write a program allowing the user to input for the
loan amount of the car and the period of years to pay.
Compute and display the monthly payments to amortize
the loan and determine the total amount at the end of the
period.
compounded interest
Formula: i
12
n = years x (12 months)
PA
1 i 1
n
i 1 i
n
Private Sub Compute_Click() Solution
Dim P, int, TotAmt, Amort As Single, term, m As Integer
P = TextBox1.Text
term = NUpDwCtr.Value * 12
int = 0.15 / 12
LB.Items.Add("Month" & vbTab & "Annuity" & vbTab & _
"Total Contribution")
Amort = (P * int * (1 + int) ^ term) / ((1 + int) ^ term - 1)
m=1
While m <= term
TotAmt = TotAmt + Amort
LB.Items.Add(m & vbTab & Amort & vbTab & TotAmt)
m=m+1
End While
End Sub
Seatwork…
Write a code that prints the angles in degrees
from 0 to 80 (step 10) and its equivalent Sine()
and Tan() in radians as follows: (Use List box)
DataGridView Component
• Displays data in a customizable grid.
• Some of DataGridView Properties:
– AllowUserToAddRows
– AllowUserToDeleteRows
– Columns
– Rows
– EditMode
– MultiSelect
– ColumnHeadersVisible
– RowHeadersVisible
Use of DataGridView
• Using DataGridView, write a code that
computes and displays the squares and cubes
of the integers from 1 to 10 with the following
output.
Private Sub Button_Click() Solution Code
Dim No, Sq, Cu As Integer
DataGridView1.Columns.Clear()
DataGridView1.Columns.Add(No, "Number")
DataGridView1.Columns.Add(Sq, "Square")
DataGridView1.Columns.Add(Cu, "Cube")
No = 1
Do While No <= 10
Sq = No ^ 2
Cu = No ^ 3
DataGridView1.Rows.Add(No, Sq, Cu)
No = No + 1
Loop
End Sub
Retrieve Data from DataGridView
x=0
Do While x <= DataGridView1.Rows.Count-1
No = DataGridView1.Rows(x).Cells(0).Value
Sq = DataGridView1.Rows(x).Cells(1).Value
Cu = DataGridView1.Rows(x).Cells(2).Value
MsgBox(No & “ ” & Sq & “ ” & Cu)
x=x+1
Loop
Assignment
Example: Use of Exit Do
• This code displays numbers from 1 to 5 even if
the final value of X is 10.
X=1
Do While X <=10
Msgbox (X)
if X = 5 then Exit Do
X=X+1
Loop
Example: Use of Exit While
• This code displays numbers from 1 to 5 even if
the final value of X is 10.
X=1
While X <=10
Msgbox (X)
if X = 5 then Exit While
X=X+1
End While
Example: Use of Exit For
• This code displays numbers from 1 to 5 even if
the final value of X is 10.
For X = 1 To 10
Msgbox (X)
if X = 5 then Exit For
Next X
Assignment
Exercise #9
Make a program that computes the distance a
body falls in feet per second, for the first 5
seconds of free fall as given by the equation:
S = ½ at2 where: S = the distance in feet
a = acceleration due to gravity (32 ft/sec2)
t = time in seconds
• Output:
Time(in sec) Distance(in ft)
1 16
2 64
3 144
4 256
5 400
Solution
Private Sub Calculate_Click()
Dim tym As Integer, dist As Single
DataGridView1.Columns.Clear()
DataGridView1.Columns.Add(tym, "Time (in sec)")
DataGridView1.Columns.Add(dist, "Distance (in ft)")
tym =1
While tym <= 5
dist = 1 / 2 * 32 * tym ^ 2
DataGridView1.Rows.Add(tym, Format(dist, "f"))
tym = tym + 1
End While
End Sub
Exercise #10
The x and y coordinates, as function of time t of a projectile
fired with an initial velocity v at an angle with respect to
the ground is given by:
x = v t cos() y = v t sin() – ½ gt2
Using these formulas, write code that allows the user to
input for the initial velocity (say 350 m/sec ) at an angle (say
25 degrees). Display a table of x (distance travelled) and y
(height) values for a projectile fired at time interval 0 to the
total time of flight (that is: t = 2 v sin() / g ) seconds with
increments of ½ second.
Vo = TextBox1.Text
Angle = TextBox2.Text
DG1.Columns.Clear()
DG1.Columns.Add(t, "Time")
DG1.Columns.Add(D, "Distance")
DG1.Columns.Add(H, "Height")
TFlight = 2 * Vo * Math.Sin(Radians(Angle)) / g
TextBox3.Text = Format(TFlight, “n2")
Solution
t=0
While t <= TFlight
D = Vo * t * Math.Cos(Radians(Angle))
H = Vo * t * Math.Sin(Radians(Angle)) - 0.5 * g * t ^ 2
DG1.Rows.Add(t, Format(D, “f"), Format(H, “f"))
t = t + 0.5
End While
t = TFlight
D = Vo * t * Math.Cos(Radians(Angle))
H = Vo * t * Math.Sin(Radians(Angle)) - 0.5 * g * t ^ 2
DGV1.Rows.Add(t, Format(D, “f"), Format(H, “f"))
End Sub
Exercise #11
Given different values (assume all are integers)
listed in the list box, determine the sum of all
the values.
2. X = 10 4. X = 100
Do While X <= 50 Do Until X > 70
X=X+5 X = X - 20
End Do Loop
Exercises
Tell how many times does each of the following loops
iterate and what is the final value of the variable ‘X’ in
each case?
5. X = 15 7. X = 75
While X <=45 Do
X=X+5 X = X + 10
if X >=30 then Exit While Loop Until X <= 10
End While
6. X = 100 8. X = 100
Do While X > 75 Do Until X > 70
X=X–5 X = X - 20
if X > 75 then Exit Do if X = 75 then Exit Do
End Do Loop
Exercises
Tell how many times does each of the following for next
loops iterate and what is the final value of the variable
‘X’ in each case?
Next
• Example:
Dim str As String
For Each str In My.Computer.FileSystem.GetDirectories("C:\")
Listbox1.Items.Add(str)
Next
Looping Exercises
Exercise 1
• Conversion of decimal number to binary:
Read a decimal number and convert the
number to its equivalent binary number.
Validate data entry for the decimal number.
Solution: Decimal to Binary
Q = Textbox1.text
do until Q = 0
Q=Q\2
loop
Recall: Decimal to Binary Conversion
• Steps/Algorithm:
st = (Q Mod 2) & st
TextBox2.Text = st
Code for Conversion
Private Sub Conversion_Click()
Dim Q As Integer
Dim st as String = “”
Q = TextBox1.Text
Do Until Q = 0
st = Q Mod 2 & st
Q=Q\2
Loop
TextBox2.Text = st
End Sub
Seatwork
• Develop codes that allow user to input for the
decimal number. Convert the number into its
equivalent:
– Octal number
– Base 9
Exercise 2
• Conversion of Decimal number to Hexadecimal:
Example:
Dim Str As String = “1101001”
bit = Mid(Str, 1, 3)
-> returns “110”
bit = Mid(Str, 7, 1)
-> returns “1"
bit = Mid(Str, 8,1)
-> Error… should not exceed length
Binary to Decimal Code
Private Sub Button1_Click()
Dim x, y, bit, total As Integer
y = Len(TextBox1.Text)
For x = 0 To y - 1
bit = Mid(TextBox1.Text, y - x, 1)
total = total + 2 ^ x * bit
Next x
TextBox2.Text = total
End Sub
Seatwork
1. Do the integer Octal to decimal conversion
code. Refer your answer to binary to decimal
code.
Syntax:
FileClose(n)
Example:
FileClose(10)
FileClose(5)
Sample Problem #1
• Read all the integer values in the file
“location\Scores.txt”. Display all numbers read
using the list box and determine and display
the sum of all the numbers.
Solution
Private Sub DisplayCompute_Click( )
Dim Idata, sum As Integer
ListBox1.Items.Clear()
FileOpen(10, “location\Scores.txt", OpenMode.Input)
Do while not ( EOF(10) )
Input(10, Idata)
ListBox1.Items.Add(Idata)
sum = sum + Idata
Loop
TextBox1.Text = sum
FileClose(10)
End Sub
Solution
Private Sub DisplayCompute_Click( )
Dim Idata As String
ListBox1.Items.Clear()
FileOpen(10, “location\Scores.txt", OpenMode.Input)
Do while not ( EOF(10) )
Input(10, Idata)
ListBox1.Items.Add(Idata)
Loop
FileClose(10)
End Sub
Sample Problem #2
• A sequential file has an unknown number of
records. Each line in the file contains the ff.
information in this order: Student name, and
with his/her 3 quiz scores obtained. Design
and write code that will read this file and
display each line in a list box.
Solution
Private Sub btnLOad_Click()
Dim Stneym, Fname As String
Dim sc1, sc2, sc3 As Integer
ListBox1.Items.Add("Student Name" & vbTab & "Quiz1" & _
vbTab & "Quiz2" & vbTab & "Quiz3")
Fname = “d:\students.txt"
FileOpen(15, Fname, OpenMode.Input)
Do Until EOF(15)
Input(15, Stneym)
Input(15, sc1)
Input(15, sc2)
Input(15, sc3)
ListBox1.Items.Add(Stneym & vbTab & sc1 & _
vbTab & sc2 & vbTab & sc3)
Loop
FileClose(15)
End Sub
Sample Problem #2b
• Revise Program in #2 so that the students
names are listed in a ComboBox as shown
below.
Private Sub Form1_Load() Solution
Dim Stneym, Fname As String
Dim sc1, sc2, sc3 As Integer
ComboBox1.Items.Clear()
FileOpen(15, "d:\students.txt", OpenMode.Input)
Do Until EOF(15)
Input(15, Stneym)
Input(15, sc1)
Input(15, sc2)
Input(15, sc3)
ComboBox1.Items.Add(Stneym)
Loop
FileClose(15)
End Sub
Sample Problem #3
• Revise the program in #1 in such a way that it
will also determine the lowest and the highest
numbers entered.
Solution
Private Sub Determine_Click( )
Dim IData, LN, HN, sum As Integer
FileOpen(10, “d:\Number.txt", OpenMode.Input)
Input(10, IData)
ListBox1.Items.Add(IData)
LN = IData ‘let the 1st number to be the HN and LN
HN = IData
sum = sum + IData
Do Until EOF(10)
Input(10, IData)
ListBox1.Items.Add(IData)
If LN > IData Then LN = IData
If HN < IData Then HN = IData
sum = sum + IData
Loop
Solution (cont.)
TextBox1.Text = sum
TextBox2.Text = LN
TextBox3.Text = HN
FileClose(10)
End Sub
Sample Problem #4
• Revise the code in Problem #2b so that you
will allow the user to input the name of the file
and its location using Inputbox( ) function.
• Use:
fname = InputBox (“Input the filename for data file”)
FileOpen(10, fname, OpenMode.Input)
fname = OFD.FileName
FileOpen(5, fname, OpenMode.Input)
EndIf
Sample
Properties of
OpenFileDialog
DefaultExt
Filename
Filter
InitialDirectory
Title
Writing data to the Sequential File
Writing data to the sequential File
• Function for output:
FileOpen(n, “filename”, OpenMode.Output)
fname = SFD.FileName.ToString
FileOpen(5, fname, OpenMode.Output)
EndIf
Case Study 1
• Problem: You’ve been hired by a law firm that is working on
a sex discrimination case. Your firm has obtained a file of
incomes, “gender.dat”, which contains the salaries for every
employee in the company being sued. Each salary amount
is preceded by “F” for female or “M” for male. As a first pass
in the analysis of this data, you’ve been asked to compute
the average income for females and the average for males.
The output should be saved in a file to be reviewed later.
• Testing: Given the ff. data in file gender.dat:
• Runtime errors
• Logic errors
Design-time error
• Known as a syntax error
• VB compiler doesn't understand your code.
• Easy to track down in VB because you will
see a blue wiggly/squiggly line pointing them
out.
• Attempting to run the program will display a
dialogue box popping up telling you that there
were Build errors.
Runtime errors
• Errors occur when the program is running.
• Exists when the program tries to do something
it shouldn't be doing.
– Example: Trying to access a file that doesn't exist.
Answer = x * y
TextBox1.Text = Answer
Try … Catch Statement
Solution to Runtime Error
Try … Catch Statement
• Built-in class (command) that deals with errors.
• The Class is called Exception. When an exception
error is found, an Exception object is created.
Syntax:
Try
<Instruction codes>
Catch ex As Exception
<Instruction codes>
[Finally ‘ ---Optional part of code
Instruction codes]
End Try
Try … Catch Statement
• Try
– means "Try to execute this code".
• Catch
– means "Catch any errors here". The ex is a
variable, and the type of variable it is an Exception
object.
• Finally
– is always executed, whether an error occurs or not.
It is used to perform any cleanup operations that
are needed.
• End Try
Example #1: Try… Catch
Try
FileOpen(5, "c:\test10.txt", OpenMode.Input)
Catch ex As Exception
Messagebox.Show (“File not found.”)
or
Msgbox(ex.Message) ------
End Try
Example #2: Try… Catch
Try
FileOpen(5, "c:\test10.txt", OpenMode.Input)
Catch ex As System.IO.FileNotFoundException
Messagebox. Show (“File not found.”)
Finally
Fileclose(5)
Exit Sub
End Try
Example #3: Try… Catch
Try
X = Inputbox(“Input Number”, “Data Entry”)
Catch ex As System.IO.FileNotFoundException
MsgBox(“Operation Cancelled…”)
Finally
Fileclose(5)
Exit Sub
End Try
End of Presentation