Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5 new The Do…Loop Statement

Similar presentations


Presentation on theme: "Chapter 5 new The Do…Loop Statement"— Presentation transcript:

1 Chapter 5 new The Do…Loop Statement
4/20/ :52 PM Chapter 5 new The Do…Loop Statement Loop structure that executes a set of statements as long as a condition is true. The condition is a Boolean expression. Executes at least once. The loop below iterates while sum is less than 10: sum = 0; Do sum += 2 Loop While sum < 10 Ask students what is the value of sum and how many times loop above executes. Bounce question. After discussing answers write console application. Lopping=iteration Type I: Do Statements Loop While condition Condition is Boolean. Statements get executed again, and again until condition becomes false. Condition is at the end so Loop executes at least once. Dim sum As Integer Dim counter As Integer sum += 2 counter += 1 Loop While sum < 10 Console.WriteLine(sum) Console.WriteLine(counter) Threading.Thread.Sleep(3000) © 2012 EMC Publishing, LLC

2 Chapter 5 Alternative Do…Loop
4/20/ :52 PM Chapter 5 Alternative Do…Loop Executes only if the condition is initially true. May not iterate at all. The statement sum = 20 Do While sum < 10 sum += 2 Loop Ask students what is the value of sum and how many times loop above executes. Bounce question. After discussing all answers modify previous app to prove how many times it executes. The same: sum=10, counter=5 ->does not iterate at all because sum is initially greater than 10. Conclusion: - Sometimes they both execute the same but sometimes not. Write ConsoleApp for both scenarios to prove difference. © 2012 EMC Publishing, LLC

3 Chapter 5 Infinite Loops
4/20/ :52 PM Chapter 5 Infinite Loops A loop that continues executing forever Can be caused by syntax or logic errors. For example: num = -1 Do num -= 1 'num is decreased by 1 Loop While num < 0 Some errors result in an overflow causing a run-time error. Set goals: what do you expect? Bounce. Write ConsoleApp for code above and prove overflow error. Run and add Watch for num. It will show 2,147,483,648 ( max range for integers but no – in front???) Logic errors can cause infinite loops which can cause an application to stop responding or just "hang". Closing the application window will end the application so that the source of the infinite loop can be located and corrected. Errors that result in an overflow may generate unexpected results rather than "hanging" the application. Write PrimeNumber Flowchart it with students participation ( see if volunteers want to do it ) and bounce answers. Private Sub btnCheck_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheck.Click Dim num As Integer = Val(Me.txtNum.Text) Dim divisor As Integer = 1 If num <= 1 Then MessageBox.Show("Not a prime number") Else Do divisor += 1 Loop While num Mod divisor <> 0 If divisor = num Then MessageBox.Show("Prime number") Me.lblDivisor.Text = divisor End If End Sub © 2012 EMC Publishing, LLC

4 Chapter 5 The InputBox Function
4/20/ :52 PM Chapter 5 The InputBox Function Displays a predefined dialog box that has a prompt, a text box, and OK and Cancel buttons, and then returns a string. Used to obtain information from the user. The function is used as part of an assignment statement: stringVar = InputBox(prompt, title) Clicking Cancel or leaving the text box blank returns Nothing. The Val() function can be used to convert string data to numeric data. - prompt is a String variable or a string enclosed in quotation marks that is displayed as a prompt in the input box. - title is an optional String variable or a string enclosed in quotation marks that is displayed in the title bar of the input box. When OK is selected the data in the text box is assigned to stringVar, a string variable. If the user selects Cancel or leaves the text box blank, Nothing is returned by the InputBox() function. Testing for Nothing is GPS. See example bellow: Ex: Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim textEntered As String textEntered = InputBox("Enter your name", "Name") If textEntered = Nothing Then Me.lblUserName.Text = "Canceled" Else Me.lblUserName.Text = textEntered End If End Sub © 2012 EMC Publishing, LLC

5 Chapter 5 Accumulator Variables
4/20/ :52 PM Chapter 5 Accumulator Variables A variable that is incremented by a varying amount. Often used for keeping a running total. Should be initialized when declared. An accumulator in an event procedure should be declared as Static so it is initialized only once. accumulator = accumulator + value Example: totalScore+=newScore ! Counter is updated always by a set amount. Accumulator is updated by value which can vary. © 2012 EMC Publishing, LLC

6 Chapter 5 Assignment Operators
4/20/ :52 PM Chapter 5 Assignment Operators Operator Operation += addition and then assignment -= subtraction and then assignement *= multiplication and then assignment /= division and then assignment \= integer division and then assignment ^= exponentiation and then assignment © 2012 EMC Publishing, LLC

7 A flag, or sentinel, indicates when a loop should stop iterating.
4/20/ :52 PM Chapter 5 Using Flags A flag, or sentinel, indicates when a loop should stop iterating. Often a constant. Code is easier to modify when sentinels are constants declared at the beginning of a procedure. Write AverageScore Flowchart it before with students participation and bouncing answers. Public Class Form1 Dim numberOfScores As Integer = 0 Dim sumOfScores As Integer = 0 Private Sub btnEnterScore_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnterScore.Click Const FLAG As Integer = -1 Dim tempScore As String numberOfScores = 0 sumOfScores = 0 tempScore = InputBox("Enter a score (-1 to stop):", "Scores") sumOfScores = Val(tempScore) Do While tempScore <> Nothing And Val(tempScore) <> FLAG sumOfScores += Val(tempScore) numberOfScores += 1 Loop Me.lblAverage.Text = sumOfScores / numberOfScores Me.lblNumberOfScores.Text = numberOfScores End Sub End Class © 2012 EMC Publishing, LLC

8 Chapter 5 The For…Next Statement
4/20/ :52 PM Chapter 5 The For…Next Statement Loop structure that executes a set of statements a fixed number of times. Uses a counter to control loop iterations. The keyword Step can optionally be used to change the amount the counter is incremented or decremented. The loop below executes until num is equal to 10: For num As Integer = 0 To 10 MessageBox.Show(num) Next num !Unlike a Do…Loop that executes while a condition is true, For…Next executes until a counter reaches an ending value. For counter As Integer = start To end Step step stepAmt statements Next counter The counter is declared in the For…Next statement. When a variable is declared like that its scope is from the initialization to the Next statement. The variable will not be recognized outside the For…Next. Write Factorial ( with InputBox(prompt, title) instead of TextBox ) Private Sub btnEnterNum_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnterNum.Click Dim number As Integer Dim factorial As Double = 1 number = InputBox("Enter number:", "Factorial") For count As Integer = 1 To number factorial *= count Next Me.lblFactorialMessage.Text = "Factorial is:" Me.lblFactorial.Text = factorial End Sub © 2012 EMC Publishing, LLC

9 Chapter 5 The String Class
4/20/ :52 PM Chapter 5 The String Class Includes properties and methods called members An object accesses a member ( property or method ) with a dot (.) between the object name and the member name. A String object is comprised of a sequence of characters with the first character at index position 0. String properties include: Chars(index) Length() The String data type is a class, which includes properties and methods called members. When a class is used to declare a variable, the variable is called an object. An object accesses a member ( property or method ) with a dot (.) between the object name and the member name. The Chars property returns the character at the specified index position. The Length property returns the number of characters in the String object. Ex: Dim season As String = "Summer" Dim letter As Char Dim numChars As Integer letter = season.Chars(4) numChars = season.Length() Console.WriteLine(letter) Console.WriteLine(numChars) © 2012 EMC Publishing, LLC

10 Chapter 5 String Methods
4/20/ :52 PM Chapter 5 String Methods String methods for manipulating a string include: ToUpper converts a string to all uppercase ToLower converts a string to all lowercase Trim removes spaces from the beginning and end of a string TrimEnd removes spaces from the end of a string TrimStart removes spaces from the beginning of a string PadLeft(len, char) adds a specified character to the beginning of a string until the string is len characters long PadRight(len, char) adds a specified character to the end of a string until the string is len characters long A method is a procedure in a class. String.Split = another Method (String(), StringSplitOptions) Returns a string array that contains the substrings in this string that are delimited by elements of a specified string array. Example: Dim words As String() = txtname.Text.Split() 'if no argument default is white-space is used to split string Ex: Dim season As String = “SummerTime” Dim newString As String newString = season.ToUpper ‘SUMMERTIME newString = season.ToLower ‘summertime season = “ SummerTime ” newString = season.Trim ‘SummerTime newString = season.TrimEnd ‘ SummerTime season = “SummerTime” newString = season.PadLeft(15, “x”) ‘xxxxxSummerTime newString = season.PadLeft(9, “x”) ‘SummerTime newString = season.PadRight(13, “x”) ‘SummerTimexxx © 2012 EMC Publishing, LLC

11 Chapter 5 String Methods (cont.)
4/20/ :52 PM Chapter 5 String Methods (cont.) String methods for manipulating a substring: Substring(startPos, numOfChars) returns the substring that is numOfChars in length and starts at startPos Remove(startPos, numOfChars) deletes the substring that is numOfChars in length and starts at startPos Replace(oldString, newString) exchanges every occurrence of oldString with newString Insert(startPos, substring) inserts substring at startPos IndexOf(substring) returns the first position of substring When using the Substring() and Remove() methods it is GPS to use first Length property to determine how many characters are in a string. ->If numOfChars exceeds the number of characters in the string a run-time error will occur. ->If IndexOf9substring() doesn’t find substring it returns -1. Dim season As String = “SummerTime” Dim newString As String Dim pos As Integer newString = season.Substring(6, 4) ‘Time newString = season.Remove(0, 6) ‘Time newString = season.Replace(“Time”, “ is fun!”) ‘Summer is fun! newString = season.Insert(6, “ is a fun “ ) ‘Summer is a fun Time Pos = season.IndexOf(“mer”) ‘3 © 2012 EMC Publishing, LLC

12 Chapter 5 String Concatenation
4/20/ :52 PM Chapter 5 String Concatenation Concatenation is joining two or more strings together. The String method Concat() joins two or more strings. It is a shared method and must be used with the String class, not an object of the class: s = String.Concat("this","and","that") The & operator can be used instead. The & operator concatenates strings: s = "this" & "and" & "that" The Concat() method is a shared method which means that it must be used with the String class, not with a particular object. ConsoleApp Example: Dim season As String = "SummerTime" Dim message As String = " is a fun time!" Dim newString As String newString = String.Concat(season, message) 'Summertime is a fun time! Console.WriteLine(season) Console.WriteLine(message) Console.WriteLine(newString)

13 Chapter 5 Space(), vbTab, vbCrLf
4/20/ :52 PM Chapter 5 Space(), vbTab, vbCrLf The Space() function returns a string of spaces. Space(numOfSpaces) vbTab is a built-in constant that represents 8 spaces. vbCrLf is a built-in constant that represents a carriage return-linefeed combination. ConsoleApp Example 1: Dim blanks As String blanks = “10” & Space(10) & “spaces” ‘ spaces Console.WriteLine(blanks) ConsoleApp Example 2: Dim message As String message = “Hello” & vbTab & vbCrLf & “Good-bye” ‘Hello and Console.WriteLine(message) ‘Good-bye

14 Chapter 5 The Char Structure
4/20/ :52 PM Chapter 5 The Char Structure Structure = a simple form of a class. Char has two shared methods: ToUpper() ToLower() The methods are shared so they must be used with the Char structure: newLetter = Char.ToUpper(letter1) © 2012 EMC Publishing, LLC

15 Two built-in functions for converting between characters and Unicode:
4/20/ :52 PM Chapter 5 Unicode A digital code with representations for every character in every language and symbol. Two built-in functions for converting between characters and Unicode: - AscW(char) -> returns the integer Unicode value of char ( a character in quotation marks or a Char variable ) - ChrW(integer) -> returns to character corresponding to integer Other functions: - StrReverse(string)-> returns string in reverse order Unicode uses 2 bytes -> 65,536 possible codes Demo: Sub Main() Console.WriteLine(AscW("a")) Console.WriteLine(ChrW(97)) End Sub Demo for StrReverse()-console: Dim TestString As String = "ABC DEFG" ' Returns "GFED CBA". Dim revString As String = StrReverse(TestString) Console.WriteLine(revString) © 2012 EMC Publishing, LLC

16 Chapter 5 Comparing Strings
4/20/ :52 PM Chapter 5 Comparing Strings When relational operators (=, >, <, >=, <=, <>) are used to compare strings, their Unicode values determine the relationship between the strings. The Compare() method is a better choice to alphabetically compare strings: Compare(string1, string2, case-insensitive) returns 0 if string1 and string2 are the same. A positive number is returned if string1 is greater/after than string2 and a negative number if string1 is less/before than string2. case-insensitive should be true if the case of the strings should not be considered. Example ( Must be Windows app with a label=lblMessage, a button=btnGo and an btnGo_Click event procedure ). Change case-insensitive from true to false. Private Sub btnGo_Click(sender As System.Object, e As System.EventArgs) Handles btnGo.Click Dim name1 As String = "Chris" Dim newname As String = "chris" If String.Compare(name1, newname, True) = 0 Then Me.lblMessage.Text = "The same." ElseIf String.Compare(name1, newname, True) > 0 Then Me.lblMessage.Text = "Alphabetically before." Me.lblMessage.Text = "Alphabetically after." End If End Sub © 2012 EMC Publishing, LLC

17 Chapter 5 The Like Operator
4/20/ :52 PM Chapter 5 The Like Operator Used to perform a textual comparison between two strings. Can be used to perform pattern matching. The pattern can include: ? used in place of any single character * used in place of many characters # used in place of any single number [] used to enclose a list of characters - used to indicate a range of characters in a list , used to separate characters in a list Example: Dim word As String Dim pattern As String word = "Run" pattern = "?un" Me.lblMessage.Text = word Like pattern 'Displays True pattern = "?um" Me.lblMessage.Text = word Like pattern 'Displays False word = "Letter to Suzy" pattern = "Letter to *" word = "Case 9876" pattern = "Case 987#" pattern = "Case ##67#" word = "C" pattern = "[A,B,C,D,E,F]" word = "B" pattern = "[A-F]" © 2012 EMC Publishing, LLC


Download ppt "Chapter 5 new The Do…Loop Statement"

Similar presentations


Ads by Google