Chapter 5 new The Do…Loop Statement

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
VBA Modules, Functions, Variables, and Constants
JavaScript, Third Edition
Repeating Program Instructions Chapter Microsoft Visual Basic.NET: Reloaded 1.
1 Lab Session-III CSIT-120 Spring 2001 Revising Previous session Data input and output While loop Exercise Limits and Bounds GOTO SLIDE 13 Lab session.
5.05 Apply Looping Structures
1.
© 2007 Lawrenceville Press Slide 1 Chapter 6 The while Statement  Loop structure that executes a set of statements as long as a condition is true  The.
Variables and Constants
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Microsoft Visual Basic 2008: Reloaded Fourth Edition
Chapter 4: The Selection Structure
COMPUTER PROGRAMMING I Objective 7.04 Apply Built-in String Functions (3%)
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 4 The If…Then Statement
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter Six Repeating Program Instructions.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Interest Calculator Application Introducing the For...Next Repetition Statements.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
08/10/ Iteration Loops For … To … Next. 208/10/2015 Learning Objectives Define a program loop. State when a loop will end. State when the For.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Chapter 12: How Long Can This Go On?
ASP.NET Programming with C# and SQL Server First Edition Chapter 5 Manipulating Strings with C#
Microsoft Visual Basic 2008: Reloaded Third Edition Chapter Six The Do Loop and List Boxes.
Introduction to Programming with RAPTOR
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
JavaScript, Fourth Edition
Chapter 3 Control Structures. The If…Then Statement The If…Then statement is a Decision statement = that executes a set of statements when a condition.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Chapter 6 Looping Structures. Do…LoopDo…Loop Statement Can operate statements repetitively Do intx=intx + 1 Loop While intx < 10 –The Loop While operates.
C++ for Engineers and Scientists Second Edition Chapter 7 Completing the Basics.
© 2006 Lawrenceville Press Slide 1 Chapter 6 The Post-Test Do…Loop Statement  Loop structure that executes a set of statements as long as a condition.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 13 How Long Can This Go On?
Controlling Program Flow with Looping Structures
5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction principles BZUPAGES.COM.
Chapter 14 JavaScript: Part II The Web Warrior Guide to Web Design Technologies.
Variables and Expressions Programming Right from the Start with Visual Basic.NET 1/e 7.
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()
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 11 So Many Paths … So Little Time.
Chapter 10 So Many Paths … So Little Time (Multiple-Alternative Selection Structures) Clearly Visual Basic: Programming with Visual Basic nd Edition.
C Language 1 Program Looping. C Language2 Topics Program looping Program looping Relational operators / expressions Relational operators / expressions.
An Introduction to Programming with C++ Sixth Edition Chapter 5 The Selection Structure.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are used in programs so that values can be represented with.
© 2006 Lawrenceville Press Slide 1 Chapter 4 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration.
Slide 1 Chapter 3 Variables  A variable is a name for a value stored in memory.  Variables are created using a declaration statement. For example: Dim.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
COMPUTER PROGRAMMING I 5.05 Apply Looping Structures.
Chapter 6 Controlling Program Flow with Looping Structures.
© 2010 Lawrenceville Press Slide 1 Chapter 5 The Do…Loop Statement  Loop structure that executes a set of statements as long as a condition is true. 
Microsoft Visual Basic 2008: Reloaded Third Edition
A variable is a name for a value stored in memory.
Controlling Program Flow with Looping Structures
The Selection Structure
Introduction to Scripting
Repeating Program Instructions
Chapter 6 The while Statement
Arrays, For loop While loop Do while loop
Making Decisions in a Program
Chapter 6 Variables What is VBScript?
Chapter 5 The Do…Loop Statement
Microsoft Visual Basic 2005: Reloaded Second Edition
Objectives After studying this chapter, you should be able to:
Chapter (3) - Looping Questions.
T. Jumana Abu Shmais – AOU - Riyadh
CIS 16 Application Development Programming with Visual Basic
Microsoft Visual Basic 2005: Reloaded Second Edition
Introduction to Computer Science
Presentation transcript:

Chapter 5 new The Do…Loop Statement 4/20/2017 12: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

Chapter 5 Alternative Do…Loop 4/20/2017 12: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

Chapter 5 Infinite Loops 4/20/2017 12: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

Chapter 5 The InputBox Function 4/20/2017 12: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

Chapter 5 Accumulator Variables 4/20/2017 12: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

Chapter 5 Assignment Operators 4/20/2017 12: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

A flag, or sentinel, indicates when a loop should stop iterating. 4/20/2017 12: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

Chapter 5 The For…Next Statement 4/20/2017 12: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

Chapter 5 The String Class 4/20/2017 12: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

Chapter 5 String Methods 4/20/2017 12: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

Chapter 5 String Methods (cont.) 4/20/2017 12: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

Chapter 5 String Concatenation 4/20/2017 12: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)

Chapter 5 Space(), vbTab, vbCrLf 4/20/2017 12: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” ‘10 spaces Console.WriteLine(blanks) ConsoleApp Example 2: Dim message As String message = “Hello” & vbTab & vbCrLf & “Good-bye” ‘Hello and Console.WriteLine(message) ‘Good-bye

Chapter 5 The Char Structure 4/20/2017 12: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

Two built-in functions for converting between characters and Unicode: 4/20/2017 12: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

Chapter 5 Comparing Strings 4/20/2017 12: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

Chapter 5 The Like Operator 4/20/2017 12: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