1 / 36

Advanced Iteration Control Techniques in Visual Basic

Learn to use do-while and for-next loops in Visual Basic to perform repetitive tasks efficiently. Explore projects like summing integers, factorials, car payment calculator, and more. Improve error handling and calculations in your applications.

jrivas
Download Presentation

Advanced Iteration Control Techniques in Visual Basic

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Index of projects in this ppt • Summing integers • Factorials • Car payment calculator • Chorelist • Interest/ payments

  3. 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

  4. 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

  5. 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

  6. 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

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

  8. 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

  9. Running the form

  10. 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

  11. The complete form

  12. Error checking

  13. More error checking

  14. 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

  15. 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)

  16. 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

  17. A Car payment calculator

  18. Add listbox to form

  19. Error checks and Calculations • Make sure data is entered in all fields

  20. 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.

  21. 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

  22. 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

  23. What else could you do? • Use try catch to check for number format error of input values.

  24. 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.

  25. 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.

  26. 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

  27. 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

  28. 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

  29. 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

  30. An interest calculator

  31. 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…

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

  33. 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

  34. Exercise: Changing the interest calculator into a loan calculator

  35. 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

  36. 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

More Related