Title: Control structures
1Control structures
- Part 2 iteration control
- To enable repetition of a statement block
2Index of projects in this ppt
- Summing integers
- Factorials
- Car payment calculator
- Chorelist
- Interest/ payments
3loops
- Syntax of the do whileloop is
- Do While boolean-expression
- Stmts
- Loop
- While, do and loop are reserved symbols.
- Use this loop to continue a processing block
4Examples 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
5Counting
- Dim count as integer
- Count0
- Do while countlt10 if countlt10 enter block
- Count1
- put other processing code here
- Loop goes back up and does it again
- more code display answer
6Adding more functionality Find sum of integers
1..10
- Dim sum,count as integer
- Sum0
- Count0
- Do while countlt10
- sum count
- Count1
- Loop
- more code display answer
7Putting code from previous slide into formload
event and displaying in a label
8Modify code above to compute 5!
- Dim prod, count As Integer
- prod 1
- Count 1
- Do While count lt 5
- prod count
- count 1
- Loop
- 'more code display answer
- lblanswer.Text "factorial of 5" prod
9Running the form
10Modify code to compute N!
- Dim prod,i,N as integer
- need to check that input value N is gt0
- Prod1
- Count1
- Do while countltN
- prod count
- Count
- Loop
- more code display answer
11The complete form
12Error checking
13More error checking
14Button click code for factorial calculations
- Dim prod, count, N As Integer
- prod 1
- count 1
- Try
- N Integer.Parse(txtinput.Text)
- If N gt 0 Then
- Do While count lt 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
15Lab exercises Compute AB and logAB
- For B an integer, AB can be computed very
similarly to N! except instead of building the
product 123N, we build the product AAAA
(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)
16Sketch of code for one lab AB
- dim B as Integer
- somehow get user input of A and B, check to
make sure B is integergt0 - Answer1
- Do while Bgt0
- Answer A
- B -1
- Loop
17A Car payment calculator
18Add listbox to form
19Error checks and Calculations
- Make sure data is entered in all fields
20Error checks and Calculations
- To calculate, youll 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.
21Code 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 lt 5
- months years 12
- monpayment Pmt(moninterest,
months, -price) - lstPayments.Items.Add("" years
ControlChars.Tab _ - monpayment.ToString("C"))
22notes
- 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
23What else could you do?
- Use try catch to check for number format error of
input values.
24For 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.
25Fornext loop
- The occurrence of the name of the index variable
after the next keyword is optional. - Once entered, start, final and increment cant be
modified to alter loop function. - Once entered, it is bad coding practice to change
the loop index with an assignment inside the
loop.
26examples
- 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
27Examples we usually count by 1s
- Dim index as integer,start,last
- Start23
- Last 407
- For index start to last
- Vb stmts go here
- Next
28Exercises 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
29Exercises 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
- Index2
- Next
30An interest calculator
31Controls and iteration
- This project uses NumericUpDown controls for data
entry, a button, some labels and a listbox. - This project uses a fornext loop instead of a do
while
32NumericUpDown set minimum, maximum, increment,
thousands separator and decimal places
33The 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.Tex
t) - 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
34Exercise Changing the interest calculator into a
loan calculator
35Project is left as an exercise
- Change button function to
- Calculate this months 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 fornext into do
whileloop
36A note about interest calculations
- In general, the calculation of interest is
- (new) principle principle(1cmprate)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 - principleprinciple(1.05/12)12