410 likes | 561 Views
ISAT 252 Visual Basic. Repetition. Assignment. Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4. Objectives. Recognize and correctly interpret conditions using both relational and logical operators Write VB code that uses loop structures For/Next Do/Loops
E N D
ISAT 252 Visual Basic Repetition
Assignment • Should have read Chapter 5 (5.1-5.5) on loops • Do tutorial 5-4
Objectives • Recognize and correctly interpret conditions using both relational and logical operators • Write VB code that uses loop structures • For/Next • Do/Loops • Use nested loops correctly • Recognize when to use each type of loop
Fundamental Program Structures • Sequence • Step by step execution of statements • Selection • Determine whether or not to execute a statement(s)based on certain condition • If –Statements, Case Statements • Iteration • Repeatedly execute one or several statements based on certain condition • Do-Loops, For-Loops All programs are combinations of these three structures.
Loops • The process of repeating a series of statements is called looping • Loop statements allow us to execute a statement multiple times • The group of repeated statements is called the body of the loop • An iteration is a single execution of the statements in the loop • All loops must have a mechanism to control the number of iterations
Control • User controlled loops – • occur when the user repeatedly triggers events, such as when entering new data • typical in event-driven programs, but not in programs using older languages • number of iterations determined by the user • Program controlled loops – • loop iterations are controlled by the programmer
Types of program control loops • Use a control mechanism • For / Next Loops • counter controlled • uses a loop index to count and control the number of iterations • changes the loop index automatically • Do / Loop • condition controlled • tests a condition to determine whether to continue looping • YOU must change the loop index value Important: You must choose the right kind of loop for the situation
For / Next Loops • Syntax: ForloopIndexVar=initial valuetofinal value [Stepincrement] body of loop Nextloop index [ ] means optional • used when the number of iterations can be determined BEFORE beginning the loop • loopIndexVarmust be a numeric variable • initial value may be any numeric variable, expression, or constant • final valuemay be any numeric variable, expression, or constant • loopIndexVar is automatically incremented in each iteration by 1 or by the Stepincrement if it is there
For Loop Action Initialization of loopIndex loopIndex condition True False Statement(s) increment
Example 1 For intLoopIndex = 1 to 5 intSquare = intLoopIndex * intLoopIndex txtOutput.Text += “x = “ + intLoopIndex.ToString() + Space(5) + _ “x ^ 2 = “ + intSquare.ToString() + vbNewLine Next intLoopIndex output: x = 1 x ^ 2 = 1 x = 2 x ^ 2 = 4 x = 3 x ^ 2 = 9 x = 4 x ^ 2 = 16 x = 5 x ^ 2 = 25 What is the initial value? What is the final value? RemembertxtOutput.Text += means txtOutput.Text = txtOutput.Text +…
Employees of Kilobytes, Inc. get a salary increase of 10% every year. Display out the salary for the next 4 years of an employee currently making $20,000. sngSalary = 20000 sngIncrease = 0.1 For intIndex = 1 to 4 sngSalary = sngSalary + sngSalary * sngIncrease txtOutput.Text += “Year: “ + intIndex.ToString() + “ Salary: “ + _ sngSalary.ToString(“c”) + vbNewLine Next intIndex output: Year: 1 Salary: $22000.00 Year: 2 Salary: Example 2
Increments • Default value is 1 • Can be changed using the Step • Examples – How many times will loop execute? For intIndex = 3 to 6 For intIndex = 3 to 10 Step 2 For sngIndex = 1 to 2 Step 0.1 For intIndex = 10 to 1 Step -1 For intIndex = 10 to 1 Step -2 DO NOT change the value of the loop index, initial value, test value, or increment in the body of the loop
Do-While/ Do-Loops • Do{While | Until} Condition • loop body • Loop Pretest Loop • Do • loop body • Loop{While | Until} Condition Posttest Loop
Do-While, Do-Until : Action condition condition False True True False statement(s) statement(s) do until loop do while loop • Loop body executes • Whilethe condition isTRUE • Loop body executes • Untilthe condition isTRUE • Both use apre-test: Test the condition before executing the body of the loop • with a pretest, loop may not execute at all
Do-Loop-While, Do-Loop-Until: Action statement statement True False condition evaluated condition evaluated False True do loop while do loop until • Loop body executes • While the condition is TRUE • Loop body executes • Until the condition is TRUE • Both use apost-test: Executes the body of the loop, then test the condition • The body of the loop is always executed at least once!!
Example Conditions • computed values • Do Until sngTotalCost >=10000 • Do While sngTotalCost < 10000 • input values • Do While intAge < 35(intAge is input data) • Do Until intAge >= 35 • end of file or sentinel markers • Do Until strUserName = “The End” • Do While strUserName <> “The End” Equivalent !!
Example 3: Credit Card payments sngBalance = … ‘give initial value to loopIndex before loop starts Do WhilesngBalance >= sngPayment intPaymentNumber = intPaymentNumber + 1 sngInterest = sngBalance * sngRate sngTotalInterest = sngTotalInterest + sngInterest sngBalance = sngBalance - sngPayment + sngInterest txtOutput.Text += “Payment Number: “ + _ intPaymentNumber.ToString() + Space(4) + _ “New Balance = “ + sngBalance.ToString() + Space(4) _ “Total Interest = “+sngTotalInterest ToString() + vbNewLine Loop
Output: Assume: sngBalance = 100, sngRate = 2% per month intPayment = 20 Payment Number: 1 New Balance = 82 Total Interest = 2 Payment Number: 2 New Balance = 63.64 Total Interest = 3.64 Payment Number: 3 New Balance = 44.91 Total Interest = 4.91 Payment Number: 4 New Balance = 25.81 Total Interest = 5.81 Payment Number: 5 New Balance = 6.33 Total Interest = 6.32
Another Example compute average of grades The user may not want to enter any grades. Therefore, we need to check the sentinel after the first input is entered before processing the grades. Initialize total to zero Initialize counter to zero Prompt for the first grade Input the first grade (possibly the sentinel) While the user has not yet entered the sentinel Add this grade to the total Add one to the grade counter Prompt for the next grade Input the next grade End While If the counter is not equal zero Set the average to the total divide by counter Else Display “ No grades were entered”
Sample Code • Private Sub btnEnterGrades_Click() handles btnGrades.click • Dim intTotal As Integer 'Sum of all grades inputs • Dim intCounter As Integer 'Number of grades input • Dim intGrade As Integer 'Current Input Grade • Dim sngAverage As Single 'Floating point average • Dim strInputMessage As String 'Text displayed in Input Box • Dim strGrade As Integer 'Current Input Grade • 'Initialization • intTotal = 0 • intCounter = 0 • strInputMessage = "Enter grades: -1 to end" • 'Processing Phase • intGrade = Cint(InputBox(strInputMessage, "Collect Grades“)) • 'Loop until intGrade has a value of -1 • Do Until intGrade = -1 • intTotal = intTotal + intGrade'Add intGrade to intTotal • intCounter = intCounter + 1'Add 1 to intCounter • ' Input a new grade • ' If the user enter the sentinel, the loop condition • ' becomes True • intGrade = CInt(InputBox(strInputMessage, "Collect Grades“)) • Loop • ‘ Termination Phase • If intCounter > 0 Then • sngAverage = intTotal / intCounter • lblAverage.Text = "The class average is " + _ • sngAverage.ToString(“f”) • Else • lblAverage.Text = "No grades were entered" • End If • End Sub • Private Sub btnExit_Click() handles cmdExit.click • End • End Sub
One more Example sngTotal = 0 Do WhilesngTotal < 25 sngNum = CSng(Inputbox(“Enter a number”)) IfsngNum > 0then sngTotal = sngTotal + sngNum^2 End If Loop
Nested Loops • Can have loops within loops • Any combination of types • Any level of nesting Do Do While Loop For J Next J Loop Until Important to indent code properly!!
Example 1 Analyze data collected by a temperature sensor which takes readings every hour for one week sngTotal=0.0 For intDayNumber = 1 to 7 For intHourNumber = 1 to 24 (process data for day = intDayNumber and hour = intHourNumber) textOutput.text += “Temperature Day “ + intDayNumber.ToString() + _ “Hour:” + intHourNumber.ToString() + _ sCurrentSensorTemperature.ToString() + vbNewLine sngTotal=sngTotal + sngCurrentSensorTemperature Next intHourNumber Next intDayNumber sngAverage= sngTotal/(7*24) textOutput.text += “Average Temperature:” + sngAverage.ToString()
Generalization of example 1 • Given a function of 2 independent integer variables: z=f(x, y) Compute z for values of x and y within a certain range. Outer loop: change X Inner loop: change Y • Problem: = Write a VB function that receives as parameters 2 positive whole numbers, x and y, and computes F(x,y)=i * (j-1)*j 0 i x 1jy • What happens if z is a function of 3 variables?
Example 2 For intI = 1 To 4 txtOutput.Text += "I = “ + intI + vbNewLine For intJ = 1 To 3 txtOutput.Text += intI.ToString() + "* " + intJ .toString() + _ " = " +(intI * intJ).toString() + vbNewLine Next intJ Next intI
Program Flow Control: Repetition • Do/Loop Pretest: Do {While | Until} Condition(Body of loop) Loop Posttest: Do (Body of loop) Loop {While | Until} Condition • For/Next ForLoopindex = InitialValuetoTestValue [StepIncrement] (Body of loop) Next [LoopIndex]
When do you use each kind of loop? • For/Next • If you know how many times you want to go through the loop • Do/Loopposttest • If you don’t know how many times you want to go through the loop AND you know you want to go through the loop at least once • Do/Looppretest – • If you don’t know how many times you want to go through the loop AND you want the option of skipping the loop altogether
Remember:Software Development Process • Analyze the problem • determine inputs and outputs • Design the solution • Identify task, sub-tasks • develop algorithms for each task and subtask • Program the solution • VB steps: create form, set properties, write code • Test and correct the solution
Sample Problem: Gathering Data Cheap Mart Inc., a local discount store, would like to be able to gather and analyze their sales data. The store is open daily from 9 - 12 noon and again from 1 - 4 pm. Write a VB program that allows the user to enter the data for any number of days, and display out the daily and grand totals.
Step 1: Analyze the problem • Determine inputs: • number of days • sales data for each day, morning and afternoon • Determine outputs: • sales data for each day • daily and grand totals
Step 2: Design the solution Start Display Table headings Read in #days Finished? yes no Read in Sales input Display totals Stop Task • Cheap Market Inc. Sales Report Subtasks: • Display table headings • Read in number of days • Read in sales input • Display Totals
Step 2: Design the solution Task: Cheap Market Inc. Sales Report Pseudocode: Initialize totals to zero Display table headings Read in the number of sales days For each day For each time period in a day Read in sales data Display sales data Add to daily total End For Display daily total Add daily total to grand total End For Display grand total How to validate?
Step 2: Design the solution Task: Read in Sales Data Pseudocode: Do Prompt a message Read Input Data If the data entered is not numeric then display a message indicating the error to the user Else If the data entered is a number less or equal than zero display a message indicating the error to the user Until input data is correct
Step 3: Write the application • Steps in creating a VB application: • Create the form(s) • Place the controls on the form 2. Set properties for each the controls • Use the naming conventions! 3. Write the code • Make code readable - naming conventions, comments, spacing and indentation, etc. • Use proper scope (most should be local) • Use forms to implement main tasks • Use sub-procedures and functions to program subtasks.
Combo Box and List Box To display a large number of choices use a combo box or a list box • The options are specified in the Items property at design time Combo Box • A combo box displays a list of options • Simple • Dropdown • The currently selected value is displayed. • When a combo box is clicked on, all of its possible values are displayed and can be selected from. List Box • A list box displays a list of options • The currently selected value is highlighted. • a scroll bar will appear on the right side of the list box allowing the user to display the remainder of the list.
Combo Boxes and List Boxes • Items can be specified • at design time (Item property) • during run time with code • Code can • access items • add items to list of items • delete items from list of items
ListBox/Combo Box Items Items property is the collection of items in the combo box/List box • Every item in the Items collection is identified by an Index • The first item in the Items collection: 0 • The second item : 1 • And so on Note: List/Combo Boxes start with 0! List Box /Combo Box Items Property 0 1 2 3 • SelectIndex property contains the index of the currently selected item • SelectItem property contains the currently selected item
Manipulate List with Code • Set first item to be selected in Form Load • lbBank.selectedIndex = 3 • cbBank.selectedIndex=3 • Remove an item • specified by its index on the Item List • lbBank.Items.removeAt(itemIndex) • cbBank.Items.removeAt(itemIndex) • Add items to list • Append the item to the list • cbBank.Items.add(“Chase Manhattan”) • lbBank.Items.add(“Chase Manhattan”) • To retrieve the current selectedItem • strBank=cbBank.SelectedItem • strBank=lbBank.SelectedItem
For Next Time: • Do Loops Activity • Do Lab 9 • Answer the Worksheet