Car Payment Calculator – Chapter 9 (loops)

Slides:



Advertisements
Similar presentations
Programming with Microsoft Visual Basic th Edition
Advertisements

Microsoft Visual Basic: Reloaded Chapter Seven More on the Repetition Structure.
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
CS0004: Introduction to Programming Repetition – Do Loops.
 Control structures  Algorithm & flowchart  If statements  While statements.
Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.
Control structures Part 2 iteration control To enable repetition of a statement block.
VB Chapters 11 & 12 Security panel app chpt 12. Textbox Properties In the Interest Calculator we have a few new properties Multi-line property set to.
Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure.
Computer Science 1620 Programming & Problem Solving.
Control Structures: Getting Started Sequence and Selection also arithmetic operators, data types, logical operators.
Repeating Program Instructions Chapter Microsoft Visual Basic.NET: Reloaded 1.
Chapter 7 – Control Structures A payroll company calculates the gross earnings per week of employees. Employees’ weekly salaries are based on the number.
5.05 Apply Looping Structures
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 6 – Car Payment Calculator Application: Introducing.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 9 Car Payment Calculator Application Introducing the Do While...Loop and Do Until...Loop.
Visual Basic Fundamental Concepts. Integrated Development Enviroment Generates startup form for new project on which to place controls. Features toolbox.
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Six Repeating Program Instructions.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Interest Calculator Application Introducing the For...Next Repetition Statements.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
06/10/ Working with Data. 206/10/2015 Learning Objectives Explain the circumstances when the following might be useful: Disabling buttons and.
Chapter 4: The Selection Process in Visual Basic.
Chapter 12: How Long Can This Go On?
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
CSCI 3327 Visual Basic Chapter 4: Control Statements in Visual Basic (Part 2) UTPA – Fall 2011 Part of the slides is from Dr. John Abraham’s previous.
 2002 Prentice Hall. All rights reserved. 1 Chapter 4: Control Structures: Part 1 Outline 4.1 Introduction 4.2 Algorithms 4.3 Pseudocode 4.4 Control Structures.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 6 – Car Payment Calculator Application: Introducing.
CSCI 3327 Visual Basic Chapter 4: Control Statements in Visual Basic (Part 1B) UTPA – Fall 2011.
1 Week 6 The Repetition Structure. 2 The Repetition Structure (Looping) Lesson A Objectives After completing this lesson, you will be able to:  Code.
Chapter 6: The Repetition Structure
Tutorial 6 The Repetition Structure
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Loop.  While Loop  Do-while Loop  For Loop Continue Statement Conclusion Loop Loop.
CS285 Visual Basic 2 Department of Computing UniS 1 Statements in Visual Basic A statement is the fundamental syntactical element of a program smallest.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Security Panel Application Introducing the Select Case Multiple-Selection Statement.
Saeed Ghanbartehrani Summer 2015 Lecture Notes #5: Programming Structures IE 212: Computational Methods for Industrial Engineering.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Class Average Application Introducing the Do...Loop While and Do...Loop Until.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
Using Java MINISTRY OF EDUCATION & HIGHER EDUCATION COLLEGE OF SCIENCE AND TECHNOLOGY KHANYOUNIS- PALESTINE Lecture 9 & 10 Repetition Statements.
Introduction to Problem Solving and Control Statements.
IE 411/511: Visual Programming for Industrial Applications Lecture Notes #5 Control Statements: Part 2.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 8.1 Test-Driving the Car Payment Calculator.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.1.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Chapter 15 I’m on the Inside; You’re on the Outside (Nested Loops) Clearly Visual Basic: Programming with Visual Basic nd Edition.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 16 I’m on the Inside; You’re on the Outside.
5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction principles BZUPAGES.COM.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
Input Boxes, List Boxes, and Loops Chapter 5. 2 Input Boxes Method for getting user’s attention to obtain input. InputBox() for obtaining input MessageBox()
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
CSCI 3327 Visual Basic Chapter 4: Control Statements in Visual Basic (Part 2B) UTPA – Fall 2011 Part of the slides is from Dr. John Abraham’s previous.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 11.1 Test-Driving the Interest Calculator Application 11.2 Essentials of Counter-Controlled Repetition.
Visual Basic Declaring Variables Dim x as Integer = 0 In the statement above, x is being declared as an Integer (whole number) and is initialised.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.-Edited By Maysoon Al-Duwais1.
Visual Basic Fundamental Concepts
while Repetition Structure
Chapter 4 C Program Control Part I
Chapter 5- Control Structures: Part 2
Tutorial 10 – Class Average Application Introducing the Do…Loop While and Do…Loop Until Repetition Statements Outline Test-Driving the Class Average.
Tutorial 9 - Car Payment Calculator Application Introducing the while Repetition Statement Outline 9.1 Test-Driving the Car Payment Calculator Application.
Control Structures: Part 2
CSCI 3327 Visual Basic Chapter 4: Control Statements in Visual Basic (Part 2B) UTPA – Fall 2011 Part of the slides is from Dr. John Abraham’s previous.
Chapter 5 – Control Structures: Part 2
Visual Basic..
Tutorial 12 – Security Panel Application Introducing the Select Case Multiple-Selection Statement Outline Test-Driving the Security Panel Application.
Chapter 3: Introduction to Problem Solving and Control Statements
3 Control Statements:.
CIS 16 Application Development Programming with Visual Basic
Introduction to Problem Solving and Control Statements
Presentation transcript:

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

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

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 = ""

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

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 =1 Do 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 - 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

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

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

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

Chapter 11 You 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 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.

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

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

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” 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

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

How it will look?

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 1006-1008 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

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()

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

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" Private Sub oneButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles oneButton.Click securityCodeTextBox.Text &= "1"

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.