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

Slides:



Advertisements
Similar presentations
Lists, Loops, Validation, and More
Advertisements

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 5- 1 STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis.
Programming with Microsoft Visual Basic 2008 Fourth Edition
Programming with Microsoft Visual Basic th Edition
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Microsoft Visual Basic: Reloaded Chapter Six Repeating Program Instructions.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Do/Loops A loop repeats a series of instructions. An iteration is a single execution of the statement(s) in the loop. Used when the exact number of iterations.
Iteration (Looping Constructs in VB) Iteration: Groups of statements which are repeatedly executed until a certain test is satisfied Carrying out Iteration.
Repeating Program Instructions Chapter Microsoft Visual Basic.NET: Reloaded 1.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
5.05 Apply Looping Structures
ISAT 252 Introduction to Arrays. Should have read 2 Chapter 8 –pp , and pp
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Six Repeating Program Instructions.
1 Chapter 6 – Repetition 6.1 Do Loops 6.2 For...Next Loops 6.3 List Boxes and Loops.
Lecture Set 5 Control Structures Part D - Repetition with Loops.
CIS 115 Lecture 8. There are 3 control structures common to most computer languages that determine the flow, or path of execution, of the code:  Sequential.
Chapter 12: How Long Can This Go On?
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Seven More on the Repetition Structure.
Chapter 6 - VB 2005 by Schneider1 Chapter 6 – Repetition 6.1 Do While and Do Until Loops 6.2 Processing Lists of Data with Do Loops 6.3 For...Next Loops.
Copyright © 2001 by Wiley. All rights reserved. Chapter 5: The Repetition Process in Visual Basic Event Driven Loops Determinate Loops Indeterminate Loops.
5-1 Chapter 5 The Repetition Process in VB.NET. 5-2 Learning Objectives Understand the importance of the repetition process in programming. Describe the.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Programming Logic and Design Fifth Edition, Comprehensive
Repetition Chapter 7. Overview u For Loop u Do Loop  Do While Loop  Do Until Loop  Do Loop While  Do Loop Until u Nested Loops.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Programming Logic and Design Sixth Edition Chapter 5 Looping.
1 Week 6 The Repetition Structure. 2 The Repetition Structure (Looping) Lesson A Objectives After completing this lesson, you will be able to:  Code.
© 2006 ITT Educational Services Inc. Introduction to Computer Programming: Unit 8: Chapter 5: Slide 1 Unit 8 List Boxes and the Do While Looping Structure.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Chapter 6: The Repetition Structure
Tutorial 6 The Repetition Structure
Microsoft Visual Basic 2008: Reloaded Third Edition Chapter Six The Do Loop and List Boxes.
Chapter 4 Looping Statements Adapted From: Starting Out with Visual Basic 2008 (Pearson)
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
‘Tirgul’ # 3 Enterprise Development Using Visual Basic 6.0 Autumn 2002 Tirgul #3.
© 2006 Pearson Education 1 More Operators  To round out our knowledge of Java operators, let's examine a few more  In particular, we will examine the.
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
CS285 Visual Basic 2 Department of Computing UniS 1 Statements in Visual Basic A statement is the fundamental syntactical element of a program smallest.
Visual Basic Programming
An Object-Oriented Approach to Programming Logic and Design Fourth Edition Chapter 4 Looping.
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.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
7-1 aslkjdhfalskhjfgalsdkfhalskdhjfglaskdhjflaskdhjfglaksjdhflakshflaksdhjfglaksjhflaksjhf.
For…Next Loops, Checked List Boxes, and Combo Boxes Chapter 5.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Controlling Program Flow with Looping Structures
Chapter Looping 5. The Increment and Decrement Operators 5.1.
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()
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
© 2006 ITT Educational Services Inc. Introduction to Computer Programming: Unit 9: Chapter 5: Slide 1 Unit 9 Do Until and For… Next Loops Chapter 5 Lists,
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
REPETITION CONTROL STRUCTURE
Tutorial 10 – Class Average Application Introducing the Do…Loop While and Do…Loop Until Repetition Statements Outline Test-Driving the Class Average.
Lists, Loops, Validation, and More
Chapter 6 – Repetition 6.1 Do Loops 6.2 For...Next Loops
Repeating Program Instructions
Chapter 6 – Repetition 6.1 Do Loops 6.2 For...Next Loops
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Microsoft Visual Basic 2005: Reloaded Second Edition
CIS 16 Application Development Programming with Visual Basic
Introduction to Problem Solving and Control Statements
Module 4 Loops and Repetition 9/19/2019 CSE 1321 Module 4.
Presentation transcript:

ISAT 252 Visual Basic Repetition

Assignment Should have read Chapter 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 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.

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

For Loop Action Statement(s) True loopIndex condition False increment Initialization of loopIndex

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 Remember txtOutput.Text += means txtOutput.Text = txtOutput.Text +… What is the initial value?What is the final value?

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 = 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: $ 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 Posttest Loop Do loop body Loop {While | Until} Condition

Do-While, Do-Until : Action statement(s) True condition False do while loop statement(s) False condition True do 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

Do-Loop-While, Do-Loop-Until: Action 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!! True condition evaluated statement False do loop while False condition evaluated statement True do loop until Loop body executes Until the condition is TRUE Loop body executes While the condition is TRUE

Example Conditions computed values Do Until sngTotalCost >=10000 Do While sngTotalCost < 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 While sngBalance >= 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 = Total Interest = 3.64 Payment Number: 3 New Balance = Total Interest = 4.91 Payment Number: 4 New Balance = Total Interest = 5.81 Payment Number: 5 New Balance = 6.33 Total Interest = 6.32

Another Example compute average of 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” 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.

The sentinel is -1

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 While sngTotal < 25 sngNum = CSng(Inputbox(“Enter a number”)) If sngNum > 0 then 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 What happens if z is a function of 3 variables? 0  i  x1jy1jy

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

When do you use each kind of 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

Remember: Software Development Process Analyze the problem Analyze the problem determine inputs and outputs Design the solution Design the solution Identify task, sub-tasks develop algorithms for each task and subtask Program the solution Program the solution VB steps: create form, set properties, write code Test and correct the solution 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 noon and again from 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 Task 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 in Sales input Display totals Stop Finished? no

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

More Controls

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

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 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 SelectIndex SelectIndex property contains the index of the currently selected item SelectItem SelectItem 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!

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