Presentation is loading. Please wait.

Presentation is loading. Please wait.

Car Payment Calculator – Chapter 9 (loops)

Similar presentations


Presentation on theme: "Car Payment Calculator – Chapter 9 (loops)"— Presentation transcript:

1 Car Payment Calculator – Chapter 9 (loops)
Use Do while, Do until loop. Use counters Introduce list boxes Concatenate strings.

2 Summary so far… Introduction to VB (Event driven, Object oriented, Visual Programming) Creating projects, forms, adding controls to the forms, changing properties of the controls, Inserting event handlers, non-visual programming. Using debugger to trouble shoot Using variables, handling text change events, using breakpoints. Control structures: sequence, selection, repetition (iteration). Formatting text, using assignment operators, display message, checkboxes. Sequence (One after the other) Selection (If-then-else) Now: Looping (Do…loop while, Do… Loop until, For …Next), Select case (another form of if-then-else) (Chapter 9-12)

3 Loops – Repetitions – Iteration
Allows programmers to specify that an action should be repeated depending on the value of a condition. Useful because sometimes you need to perform certain actions repetitively. Counter: A variable used to determine the number of times action has been repeated. Infinite loop: Logical error where exit condition is never met.

4 Different loops While … End While Do Until … Loop Do While… Loop
Do … Loop Until Do …. Loop While For … Next For each … Next So before we begin: While : Checks if the condition is true, repeats till condition stays true, stops/terminates when condition becomes false. E.g. x+=1 (while x≤10) Until : Checks if the condition is false, repeats till condition stays false, stops/terminates when condition becomes true. E.g. x+=1 (until x>10) Choice depends on your comfort level.

5 Chapter 9 Do While…loop Careful – You can go into infinite looping
Example (Pseudocode) Do while there are more items on the shopping list Purchase next item Cross it off my list ========================= Dim product AS Integer = 3 ‘Initialize prod=3 Do While product <=50 (or Do until product > 50) Product *=3 Loop Careful – You can go into infinite looping Loop Value (While –Checks for True) Value (Until –Checks for false) 1 (True) 3 (Is it less than 50) 3 (Is it greater than 50) 2 (True) 9 3 (True) 27 4 (True) 81 Exit (Condition False) 5 (False) Useful if you want to use the last value (27)

6 Car Payment Application
Typically, banks offer car loans for periods ranging from two to five years (24 to 60 months). Borrowers repay the loans in monthly installments. The amount of each monthly payment is based on the length of the loan, the amount borrowed and the interest rate. Create an application that allows the customer to enter the price of a car, the down-payment amount and the annual interest rate of the loan. The application should display the loan’s duration in months and the monthly payments for two-, three-, four- and five-year loans. The variety of options allows the user to easily compare repayment plans and choose the one that is most convenient.

7 Pseudocode for Car Payment
When user clicks calculate button Initialize loan length to two years Clear the list box of any previous results Add a header to the list box Get down payment from text box Get sticker price from text box Get interest rate from text box Calculate loan amount (Price – down payment) Calculate monthly interest (interest rate/12) Do while loan length is less than or equal to five years Convert the loan length in years to number of months Calculate monthly payment based on amount, interest, loan length Insert result into list box Increment loan length in years by one year Simple interest formula= I=PRT (Principle, Rate, Time)

8 Chapter 9 Download the template code for chapter 9 here
Add the list box to car payment calculator and rename it as paymentsListBox Add the event handler 'Clear the list box paymentsListBox.Items.Clear() ' Add the header to the list box paymentsListbox.Items.Add("Months" & ControlChars.Tab & _ Controlchars.Tab & "Monthly Payments") Add a clear button paymentsListBox.Items.Clear() downPaymentTextBox.Text = "" stickerPriceTextBox.Text = "" interestTextBox.Text = ""

9 Chapter 9 Declare variables
Dim years As Integer = 2 Dim months As Integer = 0 Dim price As Integer = 0 Dim downPayment As Integer = 0 Dim interest As Double = 0 Dim monthlyPayment As Decimal = 0 Dim loanAmount As Integer = 0 Dim totalInterest As Double = 0 Dim totalpayment As Decimal = 0 Declare variables Get users inputs and store in above variables Now the do while or do until loop Do While (years <= 5) months = years * 12 totalInterest = loanAmount * (interest / 100) * years totalpayment = loanAmount + totalInterest monthlyPayment = totalpayment / months paymentsListBox.Items.Add(months & ControlChars.Tab & ControlChars.Tab & String.Format("{0:c}", monthlyPayment)) years += 1 Loop

10 Chapter 10 Introduce Do…Loop While and Do… Loop Until
Understand counter controlled repetition Transfer the focus to a control Enable and disable buttons

11 Chapter 10 – loops Do…loop while
Like do while…loop iterates when condition is true Difference – goes into loop atleast once before testing the condition E.g. Dim counter as Integer =1 Do displayListBox.Items.Add(counter) counter +=1 Loop While counter <=3 Do…loop until is same except tests for false condition

12 Chapter 10 A teacher regularly gives quizzes to a class of 10 students. The grades on these quizzes are integers in the range from 0 to 100 (0 and 100 are both valid grades). The teacher would like you to develop an application that computes the class average for a quiz.

13 Chapter 10 - Pseudocode When the user clicks the add button
If not clear, then clear the output label and listbox Retrieve grade entered by the user in the enter grade textbox Display the grade in the list box Clear the enter grade text box Transfer focus to the enter grade text box If the user has entered more than 10 grades Disable the add grade button Transfer the focus on average button When the user clicks the average button Set total to zero set grade counter to zero Do read the next grade in the list box Add the grade to the total Add one to the grade counter Loop while the grade counter < 10 Calculate the class average Display the class average Enable the add grade button Transfer focus to the enter grade text box

14 Next Get the template from here chapter 10
Add the event handler for addButton Clear the listbox and the class average IF outputLabel.Text <> “” THEN outputLabel.Text=“” gradesListBox.Items.Clear() END IF 'display grade in listbox gradesListBox.Items.Add(Val(inputTextBox.Text)) inputTextBox.Clear() inputTextBox.Focus() If gradesListBox.Items.Count >= 10 Then addButton.Enabled = False averageButton.Enabled = True averageButton.Focus() End If

15 Next Add the event handler for the averageButton
Dim total As Integer = 0 Dim gradeCounter As Integer = 0 Dim grade As Integer = 0 Dim average As Double = 0 Do grade = gradesListBox.Items.Item(gradeCounter) total += grade gradeCounter += 1 Loop Until gradeCounter >= gradesListBox.Items.Count average = total / gradesListBox.Items.Count outputLabel.Text = String.Format("{0:f}", average) addButton.Enabled = True inputTextBox.Focus() End Sub

16 Chapter 11 Execute statements repeatedly with the For...Next repetition statement. Obtain user input with the NumericUpDown control. Display information, using a multiline TextBox. Use type String.

17 Chapter 11 Repetition loops have 4 important elements For…Next
Name of the control variable (e.g. Dim “counter”) Initial value of the control variable (e.g. “=0”) Increment or decrement in the control variable (e.g. counter+=1) Condition that tests for the final value of the control variable to determine if looping should continue (e.g. do while counter <=5) For…Next Example:

18 Chapter 11 For…next Do Until counter > 10
For counter =2 To 10 Step 2 <Body Statements> Next Equivalent do while statement Do While counter <=10 <Body Statements> counter +=2 Loop Do Until counter > 10

19 Chapter 11 You are considering investing $1, in a savings account that yields 5% interest, and you want to forecast how your investment will grow. Assuming that you will leave all interest on deposit, calculate and print the amount of money in the account at the end of each year over a period of n years. To compute these amounts, use the following formula: a = p (1 + r)n where p is the original amount of money invested (the principal) r is the annual interest rate (for example, .05 is equivalent to 5%) n is the number of years a is the amount on deposit at the end of the nth year.

20 Chapter 11 Add the numbericUpDown control
You can change the maximum/minimum/default value in the properties window. Set TextAlign=Right and ReadOnly=True Add multiLine textbox (How?) Insert normal text box  Set multiLine =True and scroll bars = vertical, readOnly=True Now create the event handler Remember [a = p (1 + r)n]

21 Chapter 11 Set the header for the multiLineTextBox Now the looping
output = “Year” & controlchars.tab & _ “Amount on Deposit” & controlChars.CrLf ControlChars.CrLf is a control character that introduces a new line character. Now the looping

22 Chapter 11 Dim principal As Decimal Dim rate As Double
Dim year As Integer Dim yearCounter As Integer Dim amount As Decimal Dim output As String 'get users inputs principal = Val(principalTextBox.Text) rate = Val(rateTextBox.Text) year = yearUpDown.Value output = "Year" & ControlChars.Tab & "Amount on Deposit" & ControlChars.CrLf For yearCounter = 1 To year amount = principal * (1 + rate / 100) ^ yearCounter output &= (yearCounter & ControlChars.Tab & String.Format("{0:c}", amount) & ControlChars.CrLf) Next resultTextBox.Text = output

23 Chapter 12 Security Panel Application – Introducing select case multiple selection statement. Use the Select Case multiple-selection statement. Use Case statements. Use the Is keyword. Obtain the current date and time. Display the date and time. Use TextBox property PasswordChar.

24 Chapter 12 If grade =“A” Then Select case grade Case “A”
Select Case Multiple Selection statement: If you have multiple If statements, you can replace them with case multiple selection statement If grade =“A” Then displayLable.Text=“Excellent” ElseIf grade=“B” Then displayLabel.Text=“Very Good” ElseIf grade=“C” Then displayLabel.Text=“Good” ElseIf grade=“D” Then displayLabel.Text=“Poor” ElseIf grade=“F” Then displayLabel.Text=“Failure” Else displayLabel.Text=“Invalid Grade” End If Select case grade Case “A” displayLabel.Text=“Excellent” Case “B” displayLabel.Text=“Very Good” Case “C” displayLabel.Text=“Good” Case “D” displayLabel.Text=“Poor” Case “F” displayLabel.Text=“Failure” Case Else displayLabel.Text=“Invalid Grade” End Select

25 Chapter 12 A lab wants to install a security panel outside a laboratory room. Only authorized personnel may enter the lab, using their security codes. The following are valid security codes (also called access codes) and the groups of employees they represent: Values Group 1645–1689 Technicians Custodians 9998, 1006–1008 Scientists Once a security code is entered, access is either granted or denied. All access attempts are written to a window below the keypad. If access is granted, the date, time and group (scientists, custodians, etc.) are written to the window. If access is denied, the date, the time and the message “Access Denied” are written to the window. Furthermore, the user can enter any one-digit access code to summon a security guard for assistance. The date, the time and the message “Restricted Access” are then written to the window to indicate that the request has been received.

26 How it will look?

27 Pseudocode When user clicks the enter (#) botton:
Retrieve security code input by user Clear input text box SELECT correct case based on access code Case where access code is less than 10 Store text “restricted access” to string variable Case where 1645 ≤ access code ≤1689 Store text “Technicians” to String Variable Case where access code equals 8345 Store text “Custodians” to String Variable Case where access code equals 9998 or b/w Case where none of the preceding cases match Store text “Access denied” to string variable DISPLAY message in listBox with current time and String variables contents

28 Developing the application
Convert the textbox to display password character by changing the PasswordChar to * Set enabled to false to prevent tampering Create the enterButton event handler Declare variables Dim accessCode As Integer Dim message As String accessCode = val(securitycodetextbox.Text securityCodeTextBox.Clear()

29 Introducing Select Case
Select Case accessCode Case Is < 10 ‘Keyword Is along with the comparison operator < specify a range of values to test message = “Restricted Access” Case 1645 to 1689 message = “Technicians” Case 8345 message = “Custodian” Case 9998, 1006 to 1008 message = “Scientist” Case Else message = “Access Denied” End Select

30 Introducing Date/Time
Add the output to the text box using following string. logEntryListBox.Items.Add(Date.Now & " " & message) Date.Now returns date and time. Now we add events to the remaining buttons 0-9 and the C button

31 Adding events 0-9 and c button
Private Sub clearButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles clearButton.Click securityCodeTextBox.Clear() End Sub Private Sub zeroButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles zeroButton.Click securityCodeTextBox.Text &= "0" Private Sub oneButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles oneButton.Click securityCodeTextBox.Text &= "1"

32 Assignment 4 Problem Download the template from the website and make the necessary changes. Problem: Download the security panel application template from the website and complete the application as discussed in the class. When you click the enter button without entering anything in the text box, it says restricted access where as it should say denied access. This shows logical error. Figure out why and fix it. Give me a printout of your reasoning and your fix.


Download ppt "Car Payment Calculator – Chapter 9 (loops)"

Similar presentations


Ads by Google