Car Payment Calculator – Chapter 9 (loops)
• Use Do while, Do until loop.
• Use counters
• Introduce list boxes
• Concatenate strings.
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)
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.
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.
Chapter 9
• Do While…loop– 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 9
3 (True) 27 27
4 (True) 81 Exit
(Condition False)
5 (False) Exit Useful if you want to use the last value (27)
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.
Pseudocode for Car PaymentWhen user clicks calculate button
Initialize loan length to two yearsClear the list box of any previous resultsAdd a header to the list box
Get down payment from text boxGet sticker price from text boxGet 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 yearsConvert the loan length in years to number of monthsCalculate monthly payment based on amount, interest, loan
lengthInsert result into list boxIncrement loan length in years by one year
Simple interest formula=
I=PRT (Principle, Rate, Time)
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 buttonpaymentsListBox.Items.Clear()downPaymentTextBox.Text = ""stickerPriceTextBox.Text = ""interestTextBox.Text = ""
Chapter 9• 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
Dim years As Integer = 2Dim months As Integer = 0Dim price As Integer = 0Dim downPayment As Integer = 0Dim interest As Double = 0Dim monthlyPayment As Decimal = 0Dim loanAmount As Integer = 0Dim totalInterest As Double = 0Dim totalpayment As Decimal = 0
Chapter 10
• Introduce Do…Loop While and Do… Loop Until
• Understand counter controlled repetition
• Transfer the focus to a control
• Enable and disable buttons
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 =1Do
displayListBox.Items.Add(counter)counter +=1
Loop While counter <=3
•Do…loop until is same except tests for false condition
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.
Chapter 10 - PseudocodeWhen 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 boxClear the enter grade text boxTransfer 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 zeroset grade counter to zeroDo 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 averageEnable the add grade buttonTransfer focus to the enter grade text box
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 listboxgradesListBox.Items.Add(Val(inputTextBox.Text))inputTextBox.Clear()inputTextBox.Focus()
If gradesListBox.Items.Count >= 10 Then
inputTextBox.Clear()addButton.Enabled = FalseaverageButton.Enabled = TrueaverageButton.Focus()
End If
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
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.
Chapter 11• Repetition loops have 4 important elements
– 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:
Chapter 11
• For…next 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<Body Statements>
counter +=2
Loop
Chapter 11You are considering investing $1,000.00 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
wherep 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 yearsa is the amount on deposit at the end of the nth year.
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]
Chapter 11• Set the header for the multiLineTextBox
output = “Year” & controlchars.tab & _
“Amount on Deposit” & controlChars.CrLf– ControlChars.CrLf is a control character that
introduces a new line character.
• Now the looping
Chapter 11Dim 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
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.
Chapter 12
If grade =“A” ThendisplayLable.Text=“Excellent”
ElseIf grade=“B” ThendisplayLabel.Text=“Very Good”
ElseIf grade=“C” ThendisplayLabel.Text=“Good”
ElseIf grade=“D” ThendisplayLabel.Text=“Poor”
ElseIf grade=“F” ThendisplayLabel.Text=“Failure”
ElsedisplayLabel.Text=“Invalid Grade”
End If
Select case gradeCase “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
Select Case Multiple Selection statement: If you have multiple If statements, you can replace them with case multiple selection statement
Chapter 12A 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 Group1645–1689 Technicians8345 Custodians9998, 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.
Pseudocode
When user clicks the enter (#) botton:Retrieve security code input by userClear input text box
SELECT correct case based on access codeCase where access code is less than 10
Store text “restricted access” to string variableCase where 1645 ≤ access code ≤1689
Store text “Technicians” to String VariableCase where access code equals 8345
Store text “Custodians” to String VariableCase where access code equals 9998 or b/w 1006-1008
Store text “Custodians” to String VariableCase where none of the preceding cases match
Store text “Access denied” to string variableDISPLAY message in listBox with current time and String variables
contents
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 variablesDim accessCode As Integer
Dim message As String
accessCode = val(securitycodetextbox.Text
securityCodeTextBox.Clear()
Introducing Select Case
Select Case accessCodeCase Is < 10 ‘Keyword Is along with the comparison operator < specify a range of values to test
message = “Restricted Access”
Case 1645 to 1689message = “Technicians”
Case 8345message = “Custodian”
Case 9998, 1006 to 1008message = “Scientist”
Case Elsemessage = “Access Denied”
End Select
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
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"• End Sub
• Private Sub oneButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles oneButton.Click
• securityCodeTextBox.Text &= "1"• End Sub
Assignment 4
• Problem 11.11 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.