36
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

  • View
    248

  • Download
    2

Embed Size (px)

Citation preview

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

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

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

loops

• Syntax of the do while…loop isDo While boolean-expression

Stmts

Loop

• While, do and loop are reserved symbols.

• Use this loop to continue a processing block

Page 4: Control structures Part 2 iteration control To enable repetition of a statement 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

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

Counting…

Dim count as integerCount=0Do while count<=10 ‘if count<=10 enter blockCount+=1‘ put other processing code hereLoop ‘ goes back up and does it again‘more code… display answer

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

Adding more functionality: Find… sum of integers 1..10

Dim sum,count as integerSum=0Count=0Do while count<=10 sum +=countCount+=1Loop‘more code… display answer

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

Putting code from previous slide into formload event and displaying in a label

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

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

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

Running the form

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

Modify code to compute N!

Dim prod,i,N as integer‘ need to check that input value N is >=0Prod=1Count=1Do while count<=N prod *=countCount++Loop‘more code… display answer

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

The complete form

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

Error checking

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

More error checking

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

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

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

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)

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

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>0Answer *=A

B -=1

Loop

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

A Car payment calculator

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

Add listbox to form

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

Error checks and Calculations

• Make sure data is entered in all fields

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

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.

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

Code for button clickPrivate 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

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

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

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

What else could you do?

• Use try catch to check for number format error of input values.

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

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.

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

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.

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

examples

• Count by 2s:Dim index as integer

For index =1 to 100 step 2

‘Vb stmts go here

Next

Count by -1sDim index as integer

For index =100 to 1 step -1

‘Vb stmts go here

Next index

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

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

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

Exercises: how many times do the following loops iterate?

‘Example 1Dim index,start,last as integerFor index =1 to 100 step 2Vb stmtsNext‘Example 2For index =100 to 1 step -5Vb stmtsNext ‘Example 3: can you provide an expression involving start and last?For index =start to last

Vb stmts

Next

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

Exercises: how many times do the following loops iterate?

‘Example 4For index =1 to 100 step -2Vb stmtsNext‘Example 5For index =101 to 100Vb stmtsNext ‘Example 6For index =1 to 100

Vb stmtsIndex=2

Next

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

An interest calculator

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

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…

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

NumericUpDown: set minimum, maximum, increment, thousands separator and decimal places

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

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

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

Exercise: Changing the interest calculator into a loan calculator

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

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

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

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