chapter 6

30
Chapter 6 Chapter 6 Controlling Program Flow Controlling Program Flow with Looping Structures with Looping Structures

Upload: paige

Post on 24-Jan-2016

38 views

Category:

Documents


0 download

DESCRIPTION

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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 6

Chapter 6Chapter 6

Controlling Program Flow with Controlling Program Flow with Looping StructuresLooping Structures

Page 2: Chapter 6

6.1 Looping6.1 Looping-Applications often need to perform repetitive tasks.-Applications often need to perform repetitive tasks.

-They use the same set of statements until a condition is met-They use the same set of statements until a condition is met

-Repeating a set of statements is called -Repeating a set of statements is called loopinglooping or or iterationiteration

Page 3: Chapter 6

6.2 The Do…Loop Statement6.2 The Do…Loop Statement-The Do…Loop executes the statements at least once before it checks -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.condition. If the condition is true it loops again until the condition is false.

-Format:-Format:

DoDo

statementsstatements

Loop While Loop While conditioncondition

--Example:Example:

Dim intNumber As Integer = 0Dim intNumber As Integer = 0

Do Do

intNumber = intNumber + 2 intNumber = intNumber + 2

Loop While intNumber < 10Loop While intNumber < 10

-How many times did the above loop execute???-How many times did the above loop execute???

Page 4: Chapter 6

6.2 Continued6.2 Continued-The Do While… Loop (Checks condition before it ever executes)-The Do While… Loop (Checks condition before it ever executes)

-Format:-Format:

Do While Do While conditioncondition

statementsstatements

LoopLoop

-How many times does a Do While … Loop have to execute???-How many times does a Do While … Loop have to execute???

Page 5: Chapter 6

6.3 Infinite Loops6.3 Infinite Loops-A condition of a loop is used to tell a loop to stop. If that condition never -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 becomes false the loop will continue forever. This is called an infinite infinite loop.loop.

-Example:-Example:

Dim intNumber As Integer = -1Dim intNumber As Integer = -1

Do While intNumber < 0Do While intNumber < 0

intNumber = intNumber -1 intNumber = intNumber -1

LoopLoop

-While will this cause an infinite 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 -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 hand corner of the title bar. Then choose end now when the dialog box appears.appears.

Page 6: Chapter 6

Ch 6 – Review 1Ch 6 – Review 1

-New Project-New Project

-New form-New form

-Add 2 labels -Add 2 labels

(lblPromt, lblResult)(lblPromt, lblResult)

-Add 1 textbox -Add 1 textbox

(txtInteger)(txtInteger)

-Add 1 button -Add 1 button

(btnTest)(btnTest)

-Add text change Event-Add text change Event

-Add btnTest Click event.-Add btnTest Click event.

Dim intTestNum As Integer = Val(Me.txtInteger.Text)

Dim intDivisor As Integer = 1If 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." Else Me.lblResult.Text = "Not a prime number." End IfEnd If

Page 7: Chapter 6

6.4 Using an Input Box6.4 Using an Input Box-It’s a predefined dialog box that has a prompt, a text box, and OK and -It’s a predefined dialog box that has a prompt, a text box, and OK and

CANCEL buttons.CANCEL buttons.

-Used to get input from the user-Used to get input from the user

-Format:-Format:

variablevariable = InputBox( = InputBox(promptprompt,, title title))

Example 1:Example 1:

Dim strName as StringDim strName as String

strName = InputBox (“Enter your full name:”, “Name”)strName = InputBox (“Enter your full name:”, “Name”)

Example 2:Example 2:

Dim intTestGrade as IntegerDim intTestGrade as Integer

intTestGrade = Val(InputBox(“Enter the test grade”, “Grade”) )intTestGrade = Val(InputBox(“Enter the test grade”, “Grade”) )

Page 8: Chapter 6

6.5 Accumulator Variables6.5 Accumulator Variables-Accumulator is a variable storing a number that’s incremented by a -Accumulator is a variable storing a number that’s incremented by a

changing value. Similar to counter variable from last chapter.changing value. Similar to counter variable from last chapter.

-Format:-Format:accumulator = accumulator + valueaccumulator = accumulator + value

-Example:-Example:Dim intTestSum, intNewTest, intNumberofTests As IntegerDim intTestSum, intNewTest, intNumberofTests As IntegerDim sngAverage as SingleDim sngAverage as Single

DoDointNewTest = Val(InputBox(“Enter test grade”, “Grade”))intNewTest = Val(InputBox(“Enter test grade”, “Grade”))intTestSum = intTestSum + intNewTestintTestSum = intTestSum + intNewTest

Loop While intNewTest <> -1Loop While intNewTest <> -1

sngAverage = intTestSum / intNumberofTestssngAverage = intTestSum / intNumberofTests

Page 9: Chapter 6

6.6 Using Flags6.6 Using Flags-Flags, or sentinels are conditions used to signify that a loop should stop -Flags, or sentinels are conditions used to signify that a loop should stop

executingexecuting

-Example:-Example:

Dim intFlag As Integer = -1Dim intFlag As Integer = -1

Dim intTestGrade, intTotal As Integer Dim intTestGrade, intTotal As Integer

DoDo

intTestGrade = Val (InputBox(“Enter test grade or (-1) to quit.”))intTestGrade = Val (InputBox(“Enter test grade or (-1) to quit.”))

if intTestGrade <> intFlag Thenif intTestGrade <> intFlag Then

intTotal = intTotal + intTestGradeintTotal = intTotal + intTestGrade

End IfEnd If

Loop While intTestGrade <> intFlag Loop While intTestGrade <> intFlag

Page 10: Chapter 6

Ch 6 – Review 2Ch 6 – Review 2-New Project-New Project

-New Form-New Form

-Add 2 buttons-Add 2 buttons

(btnEnterScores, btnAverageScore)(btnEnterScores, btnAverageScore)

-Add 5 labels-Add 5 labels

(lblInstructions, lblScoresMessage, (lblInstructions, lblScoresMessage,

lblNumberofScores, lblAverageMessage,lblNumberofScores, lblAverageMessage,

lblAverage)lblAverage)

-Add code from handout to each click event.-Add code from handout to each click event.

Page 11: Chapter 6

6.7 The For … Next Statement6.7 The For … Next Statement-A looping structure that executes a set of statements a fixed number of -A looping structure that executes a set of statements a fixed number of

timestimes

-Format:-Format:

For counter = start To end For counter = start To end

statementsstatements

Next counterNext counter

-Example 2:-Example 2: Dim intNumber As IntegerDim intNumber As Integer For intNumber = 10 to 1 Step -2For intNumber = 10 to 1 Step -2 Messagebox.show(intNumber)Messagebox.show(intNumber) Next intNumberNext intNumber

-Example 1:-Example 1: Dim intNumber As IntegerDim intNumber As Integer For intNumber = 1 to 10 Step 1For intNumber = 1 to 10 Step 1 Messagebox.show(intNumber)Messagebox.show(intNumber) Next intNumberNext intNumber

Page 12: Chapter 6

Ch 6 – Review 4Ch 6 – Review 4-New Project-New Project

-New Form-New Form

-Add 1 text box-Add 1 text box

(txtNumber)(txtNumber)

-Add 1 button -Add 1 button

(btnComputeFactorial)(btnComputeFactorial)

-Add 3 labels-Add 3 labels

(lblPrompt, lblFactorial, (lblPrompt, lblFactorial,

lblFactorialMessage)lblFactorialMessage)

-Add code to Click Event-Add code to Click Event

-Add TextChange Event-Add TextChange Event

Dim intNumber As IntegerDim lngFactorial As Long = 1Dim intCount As Integer

intNumber = Val(Me.txtNumber.Text) For intCount = 1 To intNumber lngFactorial = lngFactorial * intCountNext intCount

Me.lblFactorialMessage.Text = "Factorial is:"Me.lblFactorial.Text = lngFactorial

Page 13: Chapter 6

6.8 The String Class6.8 The String Class-The -The String String data type is a data type is a classclass

-Classes include properties and methods-Classes include properties and methods

-Properties:-Properties:

Chars(index) -> Chars(index) -> returns the character at the specific locationreturns the character at the specific location

Length ->Length -> returns the number of characters in the stringreturns the number of characters in the string

-Example 1:-Example 1:

Dim strName As String = “Ben Franklin”Dim strName As String = “Ben Franklin”

Dim intLength As IntegerDim intLength As Integer

Dim chrPosition1, chrPosition2 As Char Dim chrPosition1, chrPosition2 As Char

intLength = strName.LengthintLength = strName.Length

chrPosition1 = strName.Chars(6)chrPosition1 = strName.Chars(6)

chrPosition2 = strName.Chars(10)chrPosition2 = strName.Chars(10)

What values get stored in the 3 variables???

Page 14: Chapter 6

6.8 Continued6.8 Continued-Methods-Methods

ToUpper ->ToUpper -> converts string to upper caseconverts string to upper case

ToLower ->ToLower -> converts string to lower case converts string to lower case

Trim ->Trim -> removes spaces from beginning and end of Stringremoves spaces from beginning and end of String

TrimEnd ->TrimEnd -> removes spaces from end of Stringremoves spaces from end of String

TrimStart ->TrimStart -> removes spaces from beginning of Stringremoves spaces from beginning of String

PadLeft(length, char) ->PadLeft(length, char) -> Adds certain number of characters to Adds certain number of characters to beginning of Stringbeginning of String

PadRight(length, char) ->PadRight(length, char) -> Adds certain number of characters to Adds certain number of characters to end of Stringend of String

Page 15: Chapter 6

6.8 Continued6.8 Continued-Examples:-Examples:

Dim strSeason As String = “SummerTime”Dim strSeason As String = “SummerTime”

Dim strNewString As StringDim strNewString As String

strNewString = strSeason.ToUpperstrNewString = strSeason.ToUpper

strNewString = strSeason.ToLowerstrNewString = strSeason.ToLower

strSeason = “ SummerTime “strSeason = “ SummerTime “

strNewString = strSeason.TrimstrNewString = strSeason.Trim

strNewString = strSeason.TrimEndstrNewString = strSeason.TrimEnd

strNewString = strSeason.TrimStartstrNewString = strSeason.TrimStart

strSeason = “SummerTime”strSeason = “SummerTime”

strNewString = strSeason.PadLeft(15, “x”)strNewString = strSeason.PadLeft(15, “x”)

strNewString = strSeason.PadRight(13, “x”)strNewString = strSeason.PadRight(13, “x”)

“SUMMERTIME”“summertime”

“ SummerTime”

“SummerTime”

“SummerTime “

“xxxxxSummerTime”“SummerTimexxx”

Page 16: Chapter 6

6.8 Continued6.8 Continued-More Methods-More Methods

-Substring (start position, # of char)-Substring (start position, # of char)

-returns a portion of the string -returns a portion of the string

-Remove (start position, # of char)-Remove (start position, # of char)

-deletes a portion of the string-deletes a portion of the string

-Replace (old part, new part)-Replace (old part, new part)

-replaces every old part with the new part-replaces every old part with the new part

-Insert (start position, new part)-Insert (start position, new part)

-inserts the new part into the string at the specified location-inserts the new part into the string at the specified location

-IndexOf (search part)-IndexOf (search part)

-returns the position of the first occurrence of the search-returns the position of the first occurrence of the search

Page 17: Chapter 6

6.8 Continued6.8 Continued-More Examples:-More Examples:

Dim strSeason As String = “SummerTime”Dim strSeason As String = “SummerTime”

Dim strNewString As String Dim strNewString As String

Dim intPos As IntegerDim intPos As Integer

strNewString = strSeason.Substring(6,4)strNewString = strSeason.Substring(6,4)

strNewString = strSeason.Remove(0,6)strNewString = strSeason.Remove(0,6)

strNewString = strSeason.Replace(“Time”, “ is fun!!”)strNewString = strSeason.Replace(“Time”, “ is fun!!”)

strNewString = strSeason.Insert(6, “ is a fun ”)strNewString = strSeason.Insert(6, “ is a fun ”)

intPos = strSeason.IndexOf(“mer”)intPos = strSeason.IndexOf(“mer”)

“Time”“Time”

“Summer is fun!!”“Summer is a fun Time”

3

Page 18: Chapter 6

Ch 6 – Review 6Ch 6 – Review 6

-New Project-New Project

-New Form-New Form

-Add 1 Button-Add 1 Button

(btnCountLetter)(btnCountLetter)

-Add 2 TextBoxes-Add 2 TextBoxes

(txtText, txtSearch)(txtText, txtSearch)

-Add 4 Labels-Add 4 Labels

(lblTextPrompt, (lblTextPrompt,

lblSearchPrompt,lblSearchPrompt,

lblMessage, lblAnswer)lblMessage, lblAnswer)

-Add both Text Change Events-Add both Text Change Events

-Add code to Click Event-Add code to Click Event

Dim intChar As Integer = 0Dim strText As String = Me.txtText.TextDim strSearchText As String = Me.txtSearch.Text

strText = strText.ToLower strSearchText = strSearchText.ToLowerDim intTextLength As Integer = strText.Length

Dim intCharacter As IntegerFor intCharacter = 0 To intTextLength - 1 If strText.Chars(intCharacter) = strSearchText Then intChar = intChar + 1 End IfNext

Me.lblMessage.Text = "Number of times letter occurs:"Me.lblAnswer.Text = intChar

Page 19: Chapter 6

Ch 6 – Review 7Ch 6 – Review 7

-New Project-New Project

-New Form-New Form

-Add 1 Button-Add 1 Button

(btnDisplayData)(btnDisplayData)

-Add 1 TextBox-Add 1 TextBox

(txtWord)(txtWord)

-Add 7 Labels-Add 7 Labels

(lblPrompt, lblFirstLetter,(lblPrompt, lblFirstLetter,

lblFirst, lblMiddleLetter,lblFirst, lblMiddleLetter,

lblMiddle, lblLastLetter,lblMiddle, lblLastLetter,

lblLast)lblLast)

-Add Text Changed Event-Add Text Changed Event

-Add code to Click 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

Page 20: Chapter 6

Ch 6 – Review 8Ch 6 – Review 8-New Project-New Project

-New Form-New Form

-Add 1 Button-Add 1 Button

(btnFindString)(btnFindString)

-Add 2 TextBoxes-Add 2 TextBoxes

(txtText, txtSearch)(txtText, txtSearch)

-Add 4 Labels-Add 4 Labels

(lbltextPrompt, (lbltextPrompt,

lblSearchPrompt,lblSearchPrompt,

lblPositionMessage, lblPositionMessage,

lblAnswer)lblAnswer)

-Add 2 text changed Events-Add 2 text changed Events

-Add code to Click Event-Add code to Click Event

Dim strText As String = Me.txtText.TextDim strSearchText As String = Me.txtSearch.TextDim 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 = intPosEnd If

Page 21: Chapter 6

6.9 String Concatenation6.9 String Concatenation-2 or more strings can be joined together in a process called concatenation-2 or more strings can be joined together in a process called concatenation

-The (&) symbol can be used to join multiple strings-The (&) symbol can be used to join multiple strings

-Example:-Example:

Dim strSeason As String = “SummerTime”Dim strSeason As String = “SummerTime”

Dim strMessage As String = “ is a fun time!”Dim strMessage As String = “ is a fun time!”

Dim strNewString As StringDim strNewString As String

strNewString = strSeason & strMessage strNewString = strSeason & strMessage “SummerTime is a fun time!”“SummerTime is a fun time!”

Page 22: Chapter 6

6.9 Continued6.9 Continued-Space(# of spaces)-Space(# of spaces) can be used to enter spacescan be used to enter spaces

Example:Example:

me.lblMessage.text = “10” & space(10) & “spaces”me.lblMessage.text = “10” & space(10) & “spaces”

-vbTab-vbTab Used to tab to the next field (each field has 8 characters)Used to tab to the next field (each field has 8 characters)

Example:Example:

me.lblMessage.text = “Mr.” & vbTab & “Newton”me.lblMessage.text = “Mr.” & vbTab & “Newton”

-vbCrLf-vbCrLf Used to enter a new line Used to enter a new line

Example;Example;

me.lblMessage.text = “Mr.” & vbCrLf & “Newton”me.lblMessage.text = “Mr.” & vbCrLf & “Newton”

Page 23: Chapter 6

Ch 6 – Review 9Ch 6 – Review 9-New Project-New Project

-New Form-New Form

-Add 1 Button-Add 1 Button

(btnStart)(btnStart)

-Add 1 Label-Add 1 Label

(lblName)(lblName)

-Add code to click event-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) & strLastNameMe.lblName.Text = strFullName

Page 24: Chapter 6

6.10 The Char Structure6.10 The Char Structure-The Char data type is a structure. -The Char data type is a structure.

-A structure is a simple form of a class-A structure is a simple form of a class

-Properties-Properties

ToLower(character)ToLower(character) ->-> Changes character to lower caseChanges character to lower case

ToUpper(character)ToUpper(character) ->-> Changes character to upper caseChanges character to upper case

-Example:-Example:

Dim chrLetter As CharDim chrLetter As Char

chrLetter = Char.ToUpper(“b”)chrLetter = Char.ToUpper(“b”) “B”“B”

chrLetter = Char.ToLower(“E”)chrLetter = Char.ToLower(“E”) “e”“e”

Page 25: Chapter 6

6.11 Unicode6.11 Unicode-Every letter/symbol of every language has a unique 16-bit binary code -Every letter/symbol of every language has a unique 16-bit binary code

called UNICODEcalled UNICODE

-VB has 2 built in functions:-VB has 2 built in functions:

AscW (char)AscW (char) returns the integer Unicode valuereturns the integer Unicode value

ChrW (integer)ChrW (integer) returns the corresponding characterreturns the corresponding character

-See values on table to use functions.-See values on table to use functions.

Page 26: Chapter 6

Ch 6 – Review 10Ch 6 – Review 10-New Project-New Project

-Add form-Add form

-Add 1 button-Add 1 button

(btnStart)(btnStart)

-Add 1 label-Add 1 label

(lblCode)(lblCode)

-Add code to click event-Add code to click eventDim intNumber As IntegerDim chrUpperLetter As CharDim chrLowerLetter As CharDim intCode As IntegerFor 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

Page 27: Chapter 6

6.12 Comparing Strings6.12 Comparing Strings-Often a program will need to compare strings-Often a program will need to compare strings

-Relational operators can be used, but sometimes produces unexpected -Relational operators can be used, but sometimes produces unexpected resultsresults

-Much better to use the Compare method-Much better to use the Compare method

-Compare Method -Compare Method

Format:Format:

Compare (string1, string2, Case-sensitive)Compare (string1, string2, Case-sensitive)

-False = case sensitive, true = not 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 -if string1 is first it’s a negative number, if string2 is first it’s a positive positive number, if they’re the same its 0number, if they’re the same its 0

Page 28: Chapter 6

6.12 Continued6.12 ContinuedExample:Example:

Select String.Compare(“Chris”, “Bob”, True)Select String.Compare(“Chris”, “Bob”, True)

Case 0Case 0

lblMessage.Text = “The Same”lblMessage.Text = “The Same”

Case Is < 0Case Is < 0

lblMessage.Text = “Alphabetically before”lblMessage.Text = “Alphabetically before”

Case Is > 0Case Is > 0

lblMessage.Text = “Alphabetically after”lblMessage.Text = “Alphabetically after”

End SelectEnd Select

Page 29: Chapter 6

Ch 6 – Review 11Ch 6 – Review 11-New Project-New Project

-New Form-New Form

-Add 2 textboxes-Add 2 textboxes

(txtFirst, txtSecond)(txtFirst, txtSecond)

-Add 1 button-Add 1 button

(btnCompareWords)(btnCompareWords)

-Add 3 labels-Add 3 labels

(lblPrompt1, lblPrompt2, lblAnswer)(lblPrompt1, lblPrompt2, lblAnswer)

-Add code to Click Event-Add code to Click Event

-Add 2 Text Change Events-Add 2 Text Change EventsDim strWord1, strWord2 As StringstrWord1 = Me.txtFirst.TextstrWord2 = Me.txtSecond.TextSelect 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

Page 30: Chapter 6

6.13 The Like Operator6.13 The Like Operator