isat 252 visual basic repetition. assignment should have read chapter 5 ( 5.1-5.5) on loops do...

41
ISAT 252 ISAT 252 Visual Visual Basic Basic Repetition Repetition

Upload: brice-lucas

Post on 04-Jan-2016

221 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

ISAT 252 ISAT 252 Visual Visual BasicBasic

RepetitionRepetition

Page 2: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

AssignmentAssignment

Should have read Chapter 5 (5.1-5.5) on loops

Do tutorial 5-4

Page 3: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

ObjectivesObjectives

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

Page 4: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Fundamental Program Fundamental Program StructuresStructures

• SequenceSequence

• Step by step execution of statements

• SelectionSelection • 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.

Page 5: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

LoopsLoops

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

Page 6: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

ControlControl

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

Page 7: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Types of program control loopsTypes 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

Page 8: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

For / Next LoopsFor / Next Loops Syntax:

For loopIndexVar = initial value to final value [Step increment]

body of loop

Next loop index

[ ] means optional

used when the number of iterations can be determined BEFORE beginning the loop

loopIndexVar must be a numeric variable

initial value may be any numeric variable, expression, or constant

final value may be any numeric variable, expression, or constant

loopIndexVar is automatically incremented in each iteration by 1 or by the Step increment if it is there

Page 9: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

For Loop ActionFor Loop Action

Statement(s)

TrueTrue

loopIndexcondition

FalseFalse

increment

Initialization of loopIndex

Page 10: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Example 1Example 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 = 1x = 2 x ^ 2 = 4x = 3 x ^ 2 = 9x = 4 x ^ 2 = 16x = 5 x ^ 2 = 25

Remember txtOutput.Text += means

txtOutput.Text = txtOutput.Text +…

What is the initial value?What is the final value?

Page 11: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

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 = 20000sngIncrease = 0.1For intIndex = 1 to 4

sngSalary = sngSalary + sngSalary * sngIncreasetxtOutput.Text += “Year: “ + intIndex.ToString() + “ Salary: “ + _

sngSalary.ToString(“c”) + vbNewLineNext intIndex

output:

Year: 1 Salary: $22000.00

Year: 2 Salary:

Example Example 22

Page 12: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

IncrementsIncrements 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

Page 13: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Do-While/ Do-LoopsDo-While/ Do-Loops

Do {While | Until} Condition

loop body

Loop

Pretest Loop

Posttest Loop

Do loop body

Loop {While | Until} Condition

Page 14: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Do-While, Do-Until : Do-While, Do-Until : ActionAction

statement(s)

TrueTrue

condition

FalseFalse

do while loopdo while loop

statement(s)

FalseFalse

condition

TrueTrue

do until loopdo until loop

• Loop body executes

• Until the condition is TRUE

• Loop body executes

• While the condition is TRUE

• Both use a pre-test: Test the condition before executing the body of the loop

• with a pretest, loop may not execute at all

Page 15: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Do-Loop-While, Do-Loop-Until: Do-Loop-While, Do-Loop-Until: ActionAction

• Both use a post-test: Executes the body of the loop, then test the condition

• The body of the loop is always executed at least once!!

TrueTrue

conditionevaluated

statement

FalseFalse

do loop whiledo loop while

FalseFalse

conditionevaluated

statement

TrueTrue

do loop untildo loop until

• Loop body executes

• Until the condition is TRUE

• Loop body executes

• While the condition is TRUE

Page 16: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Example ConditionsExample 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 !!

Page 17: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Example 3: Credit Card Example 3: Credit Card paymentspayments

sngBalance = … ‘give initial value to loopIndex before loop starts

Do While sngBalance >= sngPayment

intPaymentNumber = intPaymentNumber + 1sngInterest = sngBalance * sngRatesngTotalInterest = sngTotalInterest + sngInterestsngBalance = sngBalance - sngPayment + sngInterest

txtOutput.Text += “Payment Number: “ + _ intPaymentNumber.ToString() + Space(4) + _

“New Balance = “ + sngBalance.ToString() + Space(4) _

“Total Interest = “+sngTotalInterest ToString() + vbNewLine

Loop

Page 18: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

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

Page 19: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Another Example Another Example compute average of compute average of gradesgrades

Initialize total to zeroInitialize counter to zeroPrompt for the first gradeInput the first grade (possibly the sentinel)

While the user has not yet entered the sentinel

Add this grade to the totalAdd one to the grade counterPrompt for the next gradeInput the next grade

End WhileIf the counter is not equal zero Set the average to the total divide by counter

Else Display “ No grades were entered”

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.

Page 20: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

The sentinel is -1

Page 21: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

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

Page 22: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

One more ExampleOne more Example

sngTotal = 0

Do While sngTotal < 25

sngNum = CSng(Inputbox(“Enter a number”))

If sngNum > 0 then

sngTotal = sngTotal + sngNum^2

End If

Loop

Page 23: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Nested LoopsNested 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!!

Page 24: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Example 1Example 1Analyze 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()

Page 25: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Generalization of example 1Generalization 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 XInner 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

What happens if z is a function of 3 variables?

0 i x 1jy

Page 26: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

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

Page 27: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Program Flow Control: Program Flow Control: RepetitionRepetition

Do/Loop

For Loopindex = InitialValue to TestValue [Step Increment]

(Body of loop)

Next [LoopIndex]

Pretest:

Do {While | Until} Condition

(Body of loop) Loop

Posttest:

Do

(Body of loop) Loop {While | Until} Condition

For/Next

Page 28: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

When do you use each kind of When do you use each kind of loop?loop?

For/Next If you know how many times you want to go through the loop

Do/Loop posttest 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/Loop pretest – 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

Page 29: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Remember:Remember:Software Development Software Development ProcessProcess

Analyze the problemAnalyze the problem determine inputs and outputs

Design the solutionDesign the solution Identify task, sub-tasks develop algorithms for each task and subtask

Program the solutionProgram the solution VB steps: create form, set properties, write code

Test and correct the solutionTest and correct the solution

Page 30: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Sample Problem: Gathering Sample Problem: Gathering DataData

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.

Page 31: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Step 1: Analyze the problemStep 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

Page 32: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Step 2: Design the solutionStep 2: Design the solutionTask Cheap Market Inc. Sales Report

Subtasks: Display table headings Read in number of days Read in sales input

Display Totals yes

Start

Display Table headings

Read in#days

Read inSales input

Displaytotals

Stop

Finished?

no

Page 33: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Step 2: Design the solutionStep 2: Design the solutionTask: Cheap Market Inc. Sales ReportTask: Cheap Market Inc. Sales Report

Pseudocode:Initialize totals to zeroDisplay table headingsRead in the number of sales daysFor each day

For each time period in a dayRead in sales dataDisplay sales dataAdd to daily total

End ForDisplay daily total Add daily total to grand total

End ForDisplay grand total

How to validate?

Page 34: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Step 2: Design the solutionStep 2: Design the solution

Task: Read in Sales DataTask: Read in Sales Data

Pseudocode:

DoPrompt a messageRead Input DataIf 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

Page 35: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Step 3: Write the Step 3: Write the applicationapplication

Steps in creating a VB application:1. 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.

Page 36: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

More ControlsMore Controls

Page 37: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

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 and List BoxCombo Box and List Box

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.

Page 38: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Combo Boxes and List Combo Boxes and List BoxesBoxes

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

Page 39: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

ListBox/Combo Box Items ListBox/Combo Box Items

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

First Virginia Bank

Suntrust Bank

Citibank

Farmers & Merchant Bank

List Box /Combo Box Items Property

0

1

2

3

SelectIndexSelectIndex property contains the index of the currently selected item

SelectItemSelectItem property contains the currently selected item

Items property is the collection of items in the combo box/List box

Note: List/Combo Boxes start with 0!

Page 40: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

Manipulate List with CodeManipulate 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

Page 41: ISAT 252 Visual Basic Repetition. Assignment Should have read Chapter 5 ( 5.1-5.5) on loops Do tutorial 5-4

For Next Time:For Next Time:

Do Loops Activity Do Lab 9

Answer the Worksheet