Control structures Part 2 iteration control To enable repetition of a statement block

Download Report

Transcript Control structures Part 2 iteration control To enable repetition of a statement block

Control structures
Part 2 iteration control
To enable repetition of a
statement block
Index of projects in this ppt
•
•
•
•
•
Summing integers
Factorials
Car payment calculator
Chorelist
Interest/ payments
loops
• Syntax of the do while…loop is
Do While boolean-expression
Stmts
Loop
• While, do and loop are reserved symbols.
• Use this loop to continue a processing
block
Examples of use
• Compute sums, quotients, or products of
many values.
• Process multiple entries in a list of data
• Compute compounded interest
• Approximate methods of calculus
Counting…
Dim count as integer
Count=0
Do while count<=10 ‘if count<=10 enter block
Count+=1
‘ put other processing code here
Loop ‘ goes back up and does it again
‘more code… display answer
Adding more functionality: Find…
sum of integers 1..10
Dim sum,count as integer
Sum=0
Count=0
Do while count<=10
sum +=count
Count+=1
Loop
‘more code… display answer
Putting code from previous slide into
formload event and displaying in a label
Modify code above to compute 5!
Dim prod, count As Integer
prod = 1
Count = 1
Do While count <= 5
prod *= count
count += 1
Loop
'more code… display answer
lblanswer.Text = "factorial of 5=" & prod
Running the form
Modify code to compute N!
Dim prod,i,N as integer
‘ need to check that input value N is >=0
Prod=1
Count=1
Do while count<=N
prod *=count
Count++
Loop
‘more code… display answer
The complete form
Error checking
More error checking
Button click code for factorial calculations
Dim prod, count, N As Integer
prod = 1
count = 1
Try
N = Integer.Parse(txtinput.Text)
If N >= 0 Then
Do While count <= N
prod *= count
count += 1
Loop
lblanswer.Text = "factorial of 5=" & prod
Else
lblanswer.Text = "input error"
End If
Catch ex As FormatException
lblanswer.Text = "input error"
End Try
Lab exercises: Compute AB and logAB
• For B an integer, AB can be computed very
similarly to N! except instead of building the
product 1*2*3*…*N, we build the product
A*A*A*…*A (B many times)
• logAB is the inverse of the exponential function
and, as you might guess, can be computed
inversely to our previous calculation: instead of
multiplications, do divisions. The count of
divisions until we reach 1 is an approximate
value of logAB
• (Note that VB already provides these functions
but for the lab we will write our own)
Sketch of code for one lab: AB
dim B as Integer
‘ somehow get user input of A and B, check
to make sure B is integer>=0
Answer=1
Do while B>0
Answer *=A
B -=1
Loop
A Car payment calculator
Add listbox to form
Error checks and Calculations
• Make sure data is entered in all fields
Error checks and Calculations
• To calculate, you’ll need to get input values as double or
decimal. Call them (for example) yrlyinterest,
monthlyinterest, nummonths and amount.
• Before beginning, be sure to subtract the “down
payment” from the price
• Divide yearly interest by 12 to get monthly interest
• Start year at 2 and build a loop that counts to 5 (years)
• Inside the loop call a VB function
PMT(monthlyinterest,nummonths,-amount) and print
results.
Code for button click
Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnCalc.Click
Dim years, months As Integer
Dim monpayment, down, interest, moninterest, price As Double
years = 2
lstPayments.Items.Clear()
If txtRate.Text = "" Or txtDown.Text = "" Or txtAmt.Text = "" Then ‘input error
lstPayments.Items.Add("You must enter values in all fields")
Else
price = Decimal.Parse(txtAmt.Text)
interest = Decimal.Parse(txtRate.Text)
down = Decimal.Parse(txtDown.Text)
price -= down
moninterest = interest / 12
lstPayments.Items.Add("Years" & ControlChars.Tab & "Monthly payment")
Do While years <= 5
months = years * 12
monpayment = Pmt(moninterest, months, -price)
lstPayments.Items.Add("" & years & ControlChars.Tab _
& monpayment.ToString("C"))
years += 1
Loop
End If
End Sub
notes
• I used _ to mark a continued line
• I used ControlChars.Tab to tab output
• I used lstPayments.Items.Clear() to clear listbox
contents each time the sub is entered
• I used lstPayments.Items.Add(…) to print a
heading before entering the loop
• I used
lstPayments.Items.Add("" & years &
ControlChars.Tab & monpayment.ToString("C"))
to “add” a line to the list box
What else could you do?
• Use try catch to check for number format
error of input values.
For… next loop
• Has structure
For index = start to final step increment
VB stmts
Next index
• The step increment is optional but would
allow you to count by 2, 3, -1, etc.
• If omitted the increment is 1.
For…next loop
• The occurrence of the name of the index
variable after the next keyword is optional.
• Once entered, start, final and increment
can’t be modified to alter loop function.
• Once entered, it is bad coding practice to
change the loop index with an assignment
inside the loop.
examples
• Count by 2s:
Dim index as integer
For index =1 to 100 step 2
‘Vb stmts go here
Next
Count by -1s
Dim index as integer
For index =100 to 1 step -1
‘Vb stmts go here
Next index
Examples: we usually count by 1s
Dim index as integer,start,last
Start=23
Last =407
For index =start to last
‘Vb stmts go here
Next
Exercises: how many times do the
following loops iterate?
‘Example 1
Dim index,start,last as integer
For index =1 to 100 step 2
Vb stmts
Next
‘Example 2
For index =100 to 1 step -5
Vb stmts
Next
‘Example 3: can you provide an expression involving start and last?
For index =start to last
Vb stmts
Next
Exercises: how many times do the
following loops iterate?
‘Example 4
For index =1 to 100 step -2
Vb stmts
Next
‘Example 5
For index =101 to 100
Vb stmts
Next
‘Example 6
For index =1 to 100
Vb stmts
Index=2
Next
An interest calculator
Controls and iteration
• This project uses NumericUpDown
controls for data entry, a button, some
labels and a listbox.
• This project uses a for…next loop instead
of a do while…
NumericUpDown: set minimum, maximum, increment,
thousands separator and decimal places
The code for btnCalc click event
handler
Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnCalc.Click
Dim years, count, rate As Integer
Dim amt, principle, dblrate As Double
Dim stroutput As String
years = Integer.Parse(numyears.Text) ‘get value from numericupdown
dblrate = Decimal.Parse(numrate.Text) / 100
principle = Integer.Parse(numPrinciple.Text)
For count = 1 To years
amt = principle * (dblrate)
principle += amt ‘ we can do it without exponentiation
stroutput = count.ToString() & " " & principle.ToString("C")
AccountBalance.Items.Add(stroutput)
Next 'end for..next
End Sub
Exercise: Changing the interest
calculator into a loan calculator
Project is left as an exercise
• Change button function to:
– Calculate this month’s interest
– Add interest and subtract loan amount from principle
each month
– Display output only for the years, not months. (Ie.
Every 12th month add to the display the current year
and principle remaining)
– Keep going until principle is 0.
– Clear items from listbox
– You might want to change for…next into do
while…loop
A note about interest calculations
• In general, the calculation of interest is
(new) principle= principle*(1+cmprate)^cmpinterval
• Here, cmprate and cmpinterval are the interest
rate for the compounding period and the period
itself. So, a principle at 5% per year,
compounded monthly, for one year, would be
principle=principle*(1+.05/12)^12