Controlling Program Flow with Looping Structures Chapter 6 Controlling Program Flow with Looping Structures
6.1 Looping -Applications often need to perform repetitive tasks. -They use the same set of statements until a condition is met -Repeating a set of statements is called looping or iteration
6.2 The Do…Loop Statement -The Do…Loop executes the statements at least once before it checks condition. If the condition is true it loops again until the condition is false. -Format: Do statements Loop While condition -Example: Dim intNumber As Integer = 0 intNumber = intNumber + 2 Loop While intNumber < 10 -How many times did the above loop execute???
6.2 Continued -The Do While… Loop (Checks condition before it ever executes) -Format: Do While condition statements Loop -How many times does a Do While … Loop have to execute???
6.3 Infinite Loops -A condition of a loop is used to tell a loop to stop. If that condition never becomes false the loop will continue forever. This is called an infinite loop. -Example: Dim intNumber As Integer = -1 Do While intNumber < 0 intNumber = intNumber -1 Loop -While will this cause an infinite loop??? -To stop a program stuck in an infinite loop. Just click on the x in the top left hand corner of the title bar. Then choose end now when the dialog box appears.
Ch 6 – Review 1 -New Project -New form -Add 2 labels (lblPromt, lblResult) -Add 1 textbox (txtInteger) -Add 1 button (btnTest) -Add text change Event -Add btnTest Click event. Dim intTestNum As Integer = Val(Me.txtInteger.Text) Dim intDivisor As Integer = 1 If intTestNum <= 1 Then Me.lblResult.Text = "Not a prime number." Else Do intDivisor = intDivisor + 1 Loop While intTestNum Mod intDivisor <> 0 If intDivisor = intTestNum Then Me.lblResult.Text = "Prime number." End If
6.4 Using an Input Box -It’s a predefined dialog box that has a prompt, a text box, and OK and CANCEL buttons. -Used to get input from the user -Format: variable = InputBox(prompt, title) Example 1: Dim strName as String strName = InputBox (“Enter your full name:”, “Name”) Example 2: Dim intTestGrade as Integer intTestGrade = Val(InputBox(“Enter the test grade”, “Grade”) )
6.5 Accumulator Variables -Accumulator is a variable storing a number that’s incremented by a changing value. Similar to counter variable from last chapter. -Format: accumulator = accumulator + value -Example: Dim intTestSum, intNewTest, intNumberofTests As Integer Dim sngAverage as Single Do intNewTest = Val(InputBox(“Enter test grade”, “Grade”)) intTestSum = intTestSum + intNewTest Loop While intNewTest <> -1 sngAverage = intTestSum / intNumberofTests
6.6 Using Flags -Flags, or sentinels are conditions used to signify that a loop should stop executing -Example: Dim intFlag As Integer = -1 Dim intTestGrade, intTotal As Integer Do intTestGrade = Val (InputBox(“Enter test grade or (-1) to quit.”)) if intTestGrade <> intFlag Then intTotal = intTotal + intTestGrade End If Loop While intTestGrade <> intFlag
Ch 6 – Review 2 -New Project -New Form -Add 2 buttons (btnEnterScores, btnAverageScore) -Add 5 labels (lblInstructions, lblScoresMessage, lblNumberofScores, lblAverageMessage, lblAverage) -Add code from handout to each click event.
6.7 The For … Next Statement -A looping structure that executes a set of statements a fixed number of times -Format: For counter = start To end statements Next counter -Example 1: Dim intNumber As Integer For intNumber = 1 to 10 Step 1 Messagebox.show(intNumber) Next intNumber -Example 2: Dim intNumber As Integer For intNumber = 10 to 1 Step -2 Messagebox.show(intNumber) Next intNumber
Ch 6 – Review 4 -New Project -New Form -Add 1 text box (txtNumber) -Add 1 button (btnComputeFactorial) -Add 3 labels (lblPrompt, lblFactorial, lblFactorialMessage) -Add code to Click Event -Add TextChange Event Dim intNumber As Integer Dim lngFactorial As Long = 1 Dim intCount As Integer intNumber = Val(Me.txtNumber.Text) For intCount = 1 To intNumber lngFactorial = lngFactorial * intCount Next intCount Me.lblFactorialMessage.Text = "Factorial is:" Me.lblFactorial.Text = lngFactorial
6.8 The String Class What values get stored in the 3 variables??? -The String data type is a class -Classes include properties and methods -Properties: Chars(index) -> returns the character at the specific location Length -> returns the number of characters in the string -Example 1: Dim strName As String = “Ben Franklin” Dim intLength As Integer Dim chrPosition1, chrPosition2 As Char intLength = strName.Length chrPosition1 = strName.Chars(6) chrPosition2 = strName.Chars(10) What values get stored in the 3 variables???
6.8 Continued -Methods ToUpper -> converts string to upper case ToLower -> converts string to lower case Trim -> removes spaces from beginning and end of String TrimEnd -> removes spaces from end of String TrimStart -> removes spaces from beginning of String PadLeft(length, char) -> Adds certain number of characters to beginning of String PadRight(length, char) -> Adds certain number of characters to end of String
6.8 Continued -Examples: Dim strSeason As String = “SummerTime” Dim strNewString As String strNewString = strSeason.ToUpper strNewString = strSeason.ToLower strSeason = “ SummerTime “ strNewString = strSeason.Trim strNewString = strSeason.TrimEnd strNewString = strSeason.TrimStart strSeason = “SummerTime” strNewString = strSeason.PadLeft(15, “x”) strNewString = strSeason.PadRight(13, “x”) “SUMMERTIME” “summertime” “SummerTime” “ SummerTime” “SummerTime “ “xxxxxSummerTime” “SummerTimexxx”
6.8 Continued -More Methods -Substring (start position, # of char) -returns a portion of the string -Remove (start position, # of char) -deletes a portion of the string -Replace (old part, new part) -replaces every old part with the new part -Insert (start position, new part) -inserts the new part into the string at the specified location -IndexOf (search part) -returns the position of the first occurrence of the search
6.8 Continued -More Examples: Dim strSeason As String = “SummerTime” Dim strNewString As String Dim intPos As Integer strNewString = strSeason.Substring(6,4) strNewString = strSeason.Remove(0,6) strNewString = strSeason.Replace(“Time”, “ is fun!!”) strNewString = strSeason.Insert(6, “ is a fun ”) intPos = strSeason.IndexOf(“mer”) “Time” “Time” “Summer is fun!!” “Summer is a fun Time” 3
Ch 6 – Review 6 -New Project -New Form -Add 1 Button (btnCountLetter) -Add 2 TextBoxes (txtText, txtSearch) -Add 4 Labels (lblTextPrompt, lblSearchPrompt, lblMessage, lblAnswer) -Add both Text Change Events -Add code to Click Event Dim intChar As Integer = 0 Dim strText As String = Me.txtText.Text Dim strSearchText As String = Me.txtSearch.Text strText = strText.ToLower strSearchText = strSearchText.ToLower Dim intTextLength As Integer = strText.Length Dim intCharacter As Integer For intCharacter = 0 To intTextLength - 1 If strText.Chars(intCharacter) = strSearchText Then intChar = intChar + 1 End If Next Me.lblMessage.Text = "Number of times letter occurs:" Me.lblAnswer.Text = intChar
Ch 6 – Review 7 -New Project -New Form -Add 1 Button (btnDisplayData) -Add 1 TextBox (txtWord) -Add 7 Labels (lblPrompt, lblFirstLetter, lblFirst, lblMiddleLetter, lblMiddle, lblLastLetter, lblLast) -Add Text Changed Event -Add code to Click Event Dim strText As String = Me.txtWord.Text Dim intLength As Integer = strText.Length Dim chrFirst As Char = strText.Chars(0) Dim chrMiddle As Char = strText.Chars(intLength \ 2) Dim chrLast As Char = strText.Chars(intLength - 1) Me.lblFirst.Text = chrFirst Me.lblMiddle.Text = chrMiddle Me.lblLast.Text = chrLast
Ch 6 – Review 8 -New Project -New Form -Add 1 Button (btnFindString) -Add 2 TextBoxes (txtText, txtSearch) -Add 4 Labels (lbltextPrompt, lblSearchPrompt, lblPositionMessage, lblAnswer) -Add 2 text changed Events -Add code to Click Event Dim strText As String = Me.txtText.Text Dim strSearchText As String = Me.txtSearch.Text Dim intPos As Integer = strText.IndexOf(strSearchText) If intPos = -1 Then 'not found Me.lblPositionMessage.Text = "Search text not found" Else Me.lblPositionMessage.Text = "Position of search text:" Me.lblAnswer.Text = intPos End If
6.9 String Concatenation -2 or more strings can be joined together in a process called concatenation -The (&) symbol can be used to join multiple strings -Example: Dim strSeason As String = “SummerTime” Dim strMessage As String = “ is a fun time!” Dim strNewString As String strNewString = strSeason & strMessage “SummerTime is a fun time!”
6.9 Continued -Space(# of spaces) can be used to enter spaces Example: me.lblMessage.text = “10” & space(10) & “spaces” -vbTab Used to tab to the next field (each field has 8 characters) me.lblMessage.text = “Mr.” & vbTab & “Newton” -vbCrLf Used to enter a new line Example; me.lblMessage.text = “Mr.” & vbCrLf & “Newton”
Ch 6 – Review 9 -New Project -New Form -Add 1 Button (btnStart) -Add 1 Label (lblName) -Add code to click event Dim strFirstName As String Dim strLastName As String strFirstName = InputBox("Enter your first name: ", "First Name") strLastName = InputBox("Enter your last name: ", "Last Name") Dim strFullName As String = strFirstName & Space(1) & strLastName Me.lblName.Text = strFullName
6.10 The Char Structure -The Char data type is a structure. -A structure is a simple form of a class -Properties ToLower(character) -> Changes character to lower case ToUpper(character) -> Changes character to upper case -Example: Dim chrLetter As Char chrLetter = Char.ToUpper(“b”) “B” chrLetter = Char.ToLower(“E”) “e”
6.11 Unicode -Every letter/symbol of every language has a unique 16-bit binary code called UNICODE -VB has 2 built in functions: AscW (char) returns the integer Unicode value ChrW (integer) returns the corresponding character -See values on table to use functions.
Ch 6 – Review 10 -New Project -Add form -Add 1 button (btnStart) -Add 1 label (lblCode) -Add code to click event Dim intNumber As Integer Dim chrUpperLetter As Char Dim chrLowerLetter As Char Dim intCode As Integer For intNumber = 1 To 6 chrUpperLetter = InputBox("Enter an uppercase letter") chrLowerLetter = Char.ToLower(chrUpperLetter) intCode = AscW(chrLowerLetter) Me.lblCode.Text = Me.lblCode.Text & intCode Next intNumber
6.12 Comparing Strings -Often a program will need to compare strings -Relational operators can be used, but sometimes produces unexpected results -Much better to use the Compare method -Compare Method Format: Compare (string1, string2, Case-sensitive) -False = case sensitive, true = not case sensitive -if string1 is first it’s a negative number, if string2 is first it’s a positive number, if they’re the same its 0
6.12 Continued Example: Select String.Compare(“Chris”, “Bob”, True) Case 0 lblMessage.Text = “The Same” Case Is < 0 lblMessage.Text = “Alphabetically before” Case Is > 0 lblMessage.Text = “Alphabetically after” End Select
Ch 6 – Review 11 -New Project -New Form -Add 2 textboxes (txtFirst, txtSecond) -Add 1 button (btnCompareWords) -Add 3 labels (lblPrompt1, lblPrompt2, lblAnswer) -Add code to Click Event -Add 2 Text Change Events Dim strWord1, strWord2 As String strWord1 = Me.txtFirst.Text strWord2 = Me.txtSecond.Text Select Case String.Compare(strWord1, strWord2, True) Case 0 Me.lblAnswer.Text = strWord1 & " is the same as " & strWord2 Case Is < 0 Me.lblAnswer.Text = strWord1 & " comes before " & strWord2 Case Is > 0 Me.lblAnswer.Text = strWord1 & " comes after " & strWord2 End Select
6.13 The Like Operator