Control Statements: Part 2
Transcript of Control Statements: Part 2
2
Who can control his fate?Who can control his fate?– William Shakespeare, Othello
The used key is always bright.– Benjamin Franklinj
Not everything that can be counted counts,and not every thing that counts can be counted.
– Albert Einstein
Every advantage in the past is judgedin the light of the final issue
2009 Pearson Education, Inc. All rights reserved.
in the light of the final issue.– Demosthenes
3
OBJECTIVESOBJECTIVESIn this chapter you will learn: The essentials of counter controlled repetition The essentials of counter-controlled repetition. To use the For…Next, Do…Loop While andDo Loop Until repetition statements toDo…Loop Until repetition statements to execute statements in a program repeatedly. To perform multiple selection using thep p gSelect…Case selection statement.
2009 Pearson Education, Inc. All rights reserved.
4
OBJECTIVESOBJECTIVES To use the Exit statement to break out of a
repetition statementrepetition statement. To use the Continue statement to break out
of the current iteration of a repetition statement.p To use logical operators to form more complex
conditions.
2009 Pearson Education, Inc. All rights reserved.
5
6.1 Introduction 6.2 Essentials of Counter-Controlled Repetition6.3 For…Next Repetition Statement 6 4 Examples Using the For Next Statement6.4 Examples Using the For…Next Statement 6.5 GradeBook Case Study: Select…Case
Multiple-Selection Statement 6 6 R i i S6.6 Do…Loop While Repetition Statement 6.7 Do…Loop Until Repetition Statement 6.8 Using Exit in Repetition Statements6.8 Using Exit in Repetition Statements 6.9 Using Continue in Repetition Statements 6.10 Logical Operators 6.11 (Optional) Software Engineering Case Study:
Identifying Objects’ States and Activities in the ATM System
2009 Pearson Education, Inc. All rights reserved.
6
6.2 Essentials of Counter-Controlled RepetitionRepetition
• Counter-controlled repetition requiresh f h l i bl– the name of the control variable
– the initial value– the increment (or decrement) valuethe increment (or decrement) value– the condition that tests for the final value
2009 Pearson Education, Inc. All rights reserved.
7Outline
• The example in Fig. 6.1 uses counter-controlled
1 ' Fig. 6.1: WhileCounter.vb
WhileCounter.vb
The example in Fig. 6.1 uses counter controlled repetition to display the even integers in the range 2–10.
1 Fig. 6.1: WhileCounter.vb
2 ' Using the While statement to demonstrate counter-controlled repetition.
3 Module WhileCounter
4 Sub Main()
5 Dim counter As Integer = 2 ' name and initialize loop counter
6
Initializing counterbefore the loop
6 7 While counter <= 10 ' test final value of loop counter
8 Console.Write("{0} ", counter)
9 counter += 2 ' increment counter
10 End While 1111 12 Console.WriteLine() 13 End Sub ' Main 14 End Module ' WhileCounter
2 4 6 8 10 2 4 6 8 10
Fig. 6.1 | Counter-controlled repetition with the While…End While statement.
2009 Pearson Education, Inc. All rights reserved.
8Outline
• In this For...Next statement, counter (Fig. 6.2) is
1 ' Fig. 6.2: ForCounter.vb
2 ' Using the For...Next statement for counter-controlled repetition.
3 Module ForCounter
ForCounter.vb
( 1 of 2 )
used to print even numbers from 2 to 10.
3 Module ForCounter
4 Sub Main()
5 ' initialization, repetition condition and
6 ' incrementing are all included in For...Next statement
7 For counter As Integer = 2 To 10 Step 2
8 Console.Write("{0} ", counter) 8 Console.Write( {0} , counter)
9 Next
10 11 Console.WriteLine() 12 End Sub ' Main 13 End Module ' ForCounter 13 End Module ForCounter
2 4 6 8 10
Fig. 6.2 | Counter-controlled repetition with the For…Next statement.
Good Programming Practice 6.1Place a blank line before and after each control
g | p
2009 Pearson Education, Inc. All rights reserved.
Place a blank line before and after each control statement to make it stand out in the program.
9Outline
Good Programming Practice 6.2ForCounter.vb
( 2 of 2 )
Vertical spacing above and below control statements, as well as indentation of the bodies of control statements gives programs aof control statements, gives programs atwo-dimensional appearance that enhances readability.
Error-Prevention Tip 6.1 Use a For Next loop for counter-controlledUse a For...Next loop for counter-controlled repetition. Off-by-one errors (which occur when a loop is executed for one more or one less i i h i ) d diiteration than is necessary) tend to disappear, because the terminating value is clear.
2009 Pearson Education, Inc. All rights reserved.
10
6.3 For…Next Repetition Statement (Cont.)(Cont.)
• The first line of the For…Next statement sometimes is called the For Next header (Fig 6 3)is called the For…Next header (Fig. 6.3).
Fig. 6.3 | For...Next header components.
2009 Pearson Education, Inc. All rights reserved.
11
6.3 For…Next Repetition Statement (Cont.)
• The general form of the For…Next statement is i i i li i fi lV l S i
(Cont.)
For initialization To finalValue Step incrementstatement
NextNext
• A For…Next statement can be represented byan equivalent While statement:q
initializationWhile variable <= finalValuef
statementincrement
End While
2009 Pearson Education, Inc. All rights reserved.
End While
12
6.3 For…Next Repetition Statement (Cont.)
• The counter variable may be declared before theFor Next statement:
(Cont.)
For…Next statement:Dim counter As Integer
For counter = 2 To 10 Step 2For counter = 2 To 10 Step 2Console.Write("{0} ", counter)
Next
• Values of a For…Next statement header maycontain arithmetic expressions (evaluated at start).
• If the loop-continuation condition is initially false,the For…Next’s body is not performed.
2009 Pearson Education, Inc. All rights reserved.
13
6.3 For…Next Repetition Statement (Cont.)(Cont.)
Common Programming Error 6.1Counter-controlled loops should not be controlled
i f i i i i iwith floating-point variables. Floating-point values are represented only approximately in the computer’s memory; this can lead to imprecise counter values andmemory; this can lead to imprecise counter values and inaccurate tests for termination.
2009 Pearson Education, Inc. All rights reserved.
14
6.3 For…Next Repetition Statement (Cont.)(Cont.)
Error-Prevention Tip 6.2Although the value of the control variable can bechanged in the body of a For…Next loop, avoiddoing so, because this practice can lead to subtle errors.doing so, because this practice can lead to subtle errors.
Common Programming Error 6 2Common Programming Error 6.2In nested For…Next loops, the use of the samecontrol-variable name in more than one loop is acontrol variable name in more than one loop is acompilation error.
2009 Pearson Education, Inc. All rights reserved.
15
6.3 For…Next Repetition Statement (Cont.)For counter As Integer = 1 To 10 Step 2
• The activity diagram for a For Next statement
(Cont.)
• The activity diagram for a For…Next statement (Fig. 6.4) is similar to a While statement.
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.4 | For...Next repetition statement activity diagram.
16
6.3 For… Next Repetition Statement (Cont.)
• Local type inference infers a local variable’s typebased on the context of initialization
(Cont.)
based on the context of initialization.
Di 7Dim x = 7
• The compiler infers type Integer.
Dim y = -123.45
bl• The compiler infers type Double.
2009 Pearson Education, Inc. All rights reserved.
17
6.3 For… Next Repetition Statement (Cont.)For counter As Integer = 1 To 10
Th di For Next h d b itt
(Cont.)
• The preceding For Next header can now be written as:For counter = 1 To 10
• In this case, counter is of type Integer becauseit i i iti li d ith h l b (1)it is initialized with a whole number (1).
• Local type inference can be used on any variablethat is initialized in its declarationthat is initialized in its declaration.
2009 Pearson Education, Inc. All rights reserved.
18Outline• The program in Fig. 6.5 uses a For...Next statement
to sum the even integers from 2 to 100.R b t dd f t
1 ' Fig. 6.5: Sum.vb
2 ' Using For...Next statement to demonstrate summation.
• Remember to add a reference to System.Windows.Forms.dll. Sum.vb
( 1 of 2 )g
3 Imports System.Windows.Forms
4 5 Module Sum
6 Sub Main()
7 Dim sum As Integer 0 7 Dim sum As Integer = 0
8 9 ' add even numbers from 2 to 100
10 For number = 2 To 100 Step 2 11 sum += number 12 Next 13 14 MessageBox.Show("The sum is " & sum, _ 15 "Sum even integers from 2 to 100", _ 16 MessageBoxButtons.OK, MessageBoxIcon.Information)
Method MessageBox.Showcan take four arguments.
g , g )
17 End Sub ' Main 18 End Module ' Sum
Fig. 6.5 | For…Next statement used for summation. (Part 1 of 2.)
2009 Pearson Education, Inc. All rights reserved.
19Outline
Sum.vb
( 2 of 2 )
Title bar text
Message textMessageBoxIcon.Information
MessageBoxButtons.OK
Fig 6 5 | For Next statement used for summation (Part 2 of 2 )Fig. 6.5 | For…Next statement used for summation. (Part 2 of 2.)
2009 Pearson Education, Inc. All rights reserved.
20
6.4 Examples Using the For Next Statement (Cont.)Statement (Cont.)
• Method MessageBox.Show can take four arguments.h fi h d i l b– The first two arguments are the text and title bar.
– The third argument indicates which button(s) to display.Th f th t i di t hi h i– The fourth argument indicates which icon appears.
2009 Pearson Education, Inc. All rights reserved.
21
6.4 Examples Using the For Next Statement (Cont.)Statement (Cont.)
MessageBoxIcon constants Icon Description
i MessageBoxIcon.Warning or MessageBoxIcon.Exclamation
Used to caution the user against potential problems.
MessageBoxIcon.Information Used to display information about the state of the applicationapplication.
MessageBoxIcon.None No icon is displayed.
MessageBoxIcon.Error Used to alert the user to errors or critical situations.
Fig. 6.6 | Message dialog icon constants.
2009 Pearson Education, Inc. All rights reserved.
22
6.4 Examples Using the For Next Statement (Cont.)Statement (Cont.)
MessageBoxButton constants Description
MessageBoxButtons.OK OK button Allows the user to acknowledge aessage o utto s O OK button. Allows the user to acknowledge a message. Included by default.
MessageBoxButtons.OKCancel OK and Cancel buttons. Allow the user to either continue or cancel an operation.
Fig. 6.7 | Message dialog button constants. (Part 1 of 2.)
MessageBoxButtons.YesNo Yes and No buttons. Allow the user to respond to a question.
2009 Pearson Education, Inc. All rights reserved.
23
6.4 Examples Using the For Next Statement (Cont.)Statement (Cont.)
MessageBoxButton constants Description
MessageBoxButtons.YesNoCancel Yes No and Cancel buttons Allow theg Yes, No and Cancel buttons. Allow the user to respond to a question or cancel an operation.
MessageBoxButtons.RetryCancel Retry and Cancel buttons. Allow the user to retry or cancel an operation that has failed.to retry or cancel an operation that has failed.
MessageBoxButtons.AbortRetryIgnore Abort, Retry and Ignore buttons. When one of a series of operations has failed, these buttons allow the user to abort the entire sequence, retry the failed operation or ignore q , y p gthe failed operation and continue.
Fig. 6.7 | Message dialog button constants. (Part 2 of 2.)
2009 Pearson Education, Inc. All rights reserved.
24
6.4 Examples Using the For Next Statement (Cont.)
• Consider the following problem statement:
Statement (Cont.)
A person invests $1000.00 in a savings account that yields 5% interest. Calculate the amount of money in the account at the end of each year over a period ofthe account at the end of each year over a period of 10 years. Use the following formula:
a = p (1 + r) na = p (1 + r) n
2009 Pearson Education, Inc. All rights reserved.
25
1 ' Fig. 6.8: Interest.vb
2 ' Calculating compound interest.
3 Imports System.Windows.Forms
Outline
4 5 Module Interest
6 Sub Main()
7 Dim amount As Decimal ' dollar amounts on deposit
8 Dim principal As Decimal = 1000.00 ' amount invested
Interest.vb
( 1 of 3 )
9 Dim rate As Double = 0.05 ' interest rate
10 11 ' amount after each year 12 Dim output As String = _ 13 "Year" & vbTab & "Amount on deposit" & vbNewLine
amount and principalare declared as type Decimal3 ea & b ab & ou t o depos t & b e e
14 15 ' calculate amount after each year 16 For yearValue = 1 To 10 17 amount = principal * (1 + rate) ^ yearValue 18 output &= yearValue & vbTab & String Format("{0:C}" amount)
Calculating interest foreach year
18 output &= yearValue & vbTab & String.Format( {0:C} , amount) _
19 & vbNewLine 20 Next 21 22 ' display output 23 MessageBox Show(output "Compound Interest"
String.Formatformats text as directed
23 MessageBox.Show(output, Compound Interest , _
24 MessageBoxButtons.OK, MessageBoxIcon.Information) 25 End Sub ' Main 26 End Module ' Interest
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.8 | For…Next statement used to calculatecompound interest. (Part 1 of 2.)
26Outline
Interest.vb
( 2 of 3 )
Fig. 6.8 | For…Next statement used to calculated i t t (P t 2 f 2 )compound interest. (Part 2 of 2.)
2009 Pearson Education, Inc. All rights reserved.
27Outline
Error-Prevention Tip 6.3Interest.vb
( 3 of 3 )
o e e t o p 6 3Do not use variables of type Single or Double to perform precise monetary calculations. The imprecision
f fl ti i t b th t lt iof floating-point numbers can cause errors that result in incorrect monetary values. Use the type Decimal for monetary calculations.
Performance Tip 6.1Avoid placing inside a loop the calculation of an expression whose value does not change each time through the loop. Such an expression should be evaluated only once andSuch an expression should be evaluated only once and prior to the loop.
2009 Pearson Education, Inc. All rights reserved.
28Outline
• The GradeBook class now uses the Select...Casem ltiple selection statement (Fi 6 9)
1 ' Fig. 6.9: GradeBook.vb
2 ' GradeBook class uses Select...Case statement to count letter grades.
3 Public Class GradeBook
GradeBook.vb
( 1 of 6 )
multiple-selection statement (Fig. 6.9).
4 Private courseNameValue As String ' name of course
5 Private total As Integer ' sum of grades
6 Private gradeCounter As Integer ' number of grades entered
7 Private aCount As Integer ' count of A grades
8 Private bCount As Integer ' count of B grades 8 Private bCount As Integer count of B grades
9 Private cCount As Integer ' count of C grades
10 Private dCount As Integer ' count of D grades 11 Private fCount As Integer ' count of F grades 12 Private perfectScoreCount As Integer ' count of perfect scores 1313 14 ' constructor initializes course name; 15 ' Integer instance variables are initialized to 0 by default 16 Public Sub New(ByVal name As String) 17 CourseName = name ' initializes CourseName 18 End Sub ' New 19
Fig. 6.9 | GradeBook class uses Select…Case statement to countA B C D d F d (P t 1 f 6 )
2009 Pearson Education, Inc. All rights reserved.
A, B, C, D and F grades. (Part 1 of 6.)
29Outline
20 ' property that gets and sets the course name; the Set accessor 21 ' ensures that the course name has at most 25 characters 22 Public Property CourseName() As String 23 Get ' retrieve courseNameValue 24 Return courseNameValue
GradeBook.vb
( 2 of 6 )24 Return courseNameValue 25 End Get 26 27 Set(ByVal value As String) ' set courseNameValue 28 If value.Length <= 25 Then ' if value has 25 or fewer characters 29 courseNameValue = value ' store the course name in the object 30 Else ' if name has more than 25 characters 31 ' set courseNameValue to first 25 characters of parameter name 32 ' start at 0, length of 25 33 courseNameValue = value.Substring(0, 25) 33 courseNameValue value.Substring(0, 25)
34 35 Console.WriteLine( _ 36 "Course name (" & value & ") exceeds maximum length (25).") 37 Console.WriteLine( _ 38 "Limiting course name to first 25 characters " & vbNewLine) 38 "Limiting course name to first 25 characters." & vbNewLine) 39 End If 40 End Set 41 End Property ' CourseName
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.9 | GradeBook class uses Select…Case statement to countA, B, C, D and F grades. (Part 2 of 6.)
30Outline
42 43 ' display a welcome message to the GradeBook user 44 Public Sub DisplayMessage()
GradeBook.vb
( 3 of 6 )
45 Console.WriteLine("Welcome to the grade book for " _ 46 & vbNewLine & CourseName & "!" & vbNewLine) 47 End Sub ' DisplayMessage 48 49 ' input arbitrary number of grades from user 49 input arbitrary number of grades from user
50 Public Sub InputGrades() 51 Console.Write( _ 52 "Enter the grades in the range 0-100, negative value to quit: ") 53 Dim grade As Integer = Console.ReadLine() ' input first grade 5454 55 ' loop until user enters a sentinel value
56 While grade >= 0 57 total += grade ' add grade to total 58 gradeCounter += 1 ' increment number of grades 59
Fig. 6.9 | GradeBook class uses Select…Case statement to countA, B, C, D and F grades. (Part 3 of 6.)
2009 Pearson Education, Inc. All rights reserved.
31Outline
60 ' call method to increment appropriate counter 61 IncrementLetterGradeCounter(grade) 62
GradeBook.vb
( 4 of 6 )
63 ' input next grade 64 Console.Write("Enter the grades in the range 0-100, " & _ 65 "negative value to quit: ") 66 grade = Console.ReadLine() 67 End While 68 End Sub ' InputGrades 69 70 ' add 1 to appropriate counter for specified grade 71 Private Sub IncrementLetterGradeCounter(ByVal grade As Integer) 72 Select Case grade ' determine which grade was entered
Using a Select...Casestatement to determine g g
73 Case 100 ' perfect score 74 perfectScoreCount += 1 ' increment perfectScoreCount 75 aCount += 1 ' increment aCount 76 Case 90 To 99 ' grade was between 90 and 99 77 aCount += 1 ' increment aCount
which counter to increment.
77 aCount += 1 increment aCount
Fig. 6.9 | GradeBook class uses Select…Case statement to countA, B, C, D and F grades. (Part 4 of 6.)
2009 Pearson Education, Inc. All rights reserved.
32Outline
78 Case 80 To 89 ' grade was between 80 and 89 79 bCount += 1 ' increment bCount 80 Case 70 To 79 ' grade was between 70 and 79
GradeBook.vb
( 5 of 6 )
81 cCount += 1 ' increment cCount 82 Case 60 To 69 ' grade was between 60 and 69 83 dCount += 1 ' increment dCount 84 Case Else ' grade was less than 60 85 fCount += 1 ' increment fCount 86 End Select 87 End Sub ' IncrementLetterGradeCounter 88 89 ' display a report based on the grades entered by user 90 Public Sub DisplayGradeReport() p y p ()
91 Console.WriteLine(vbNewLine & "Grade Report:") 92 93 ' if user entered at least one grade 94 If (gradeCounter > 0) Then 95 ' calculate average of all grades entered 95 calculate average of all grades entered
96 Dim average As Double = total / gradeCounter
Fig. 6.9 | GradeBook class uses Select…Case statement to countA, B, C, D and F grades. (Part 5 of 6.)
2009 Pearson Education, Inc. All rights reserved.
, , , g ( )
33Outline
97 98 ' output summary of results 99 Console.WriteLine("Total of the {0} grades entered is {1}", _
GradeBook.vb
( 6 of 6 )
100 gradeCounter, total) 101 Console.WriteLine("Class average is {0:F2}", average) 102 Console.WriteLine("Number of students who received each grade:") 103 Console.WriteLine("A: " & aCount) ' display number of A grades 104 Console WriteLine("B: " & bCount) ' display number of B grades 104 Console.WriteLine( B: & bCount) display number of B grades
105 Console.WriteLine("C: " & cCount) ' display number of C grades
106 Console.WriteLine("D: " & dCount) ' display number of D grades 107 Console.WriteLine("F: " & fCount) ' display number of F grades 108 Console.WriteLine(vbNewLine & "Number of students who " & _ 109 " i d f " & f ) 109 "received perfect scores: " & perfectScoreCount) 110 Else ' no grades were entered, so output appropriate message 111 Console.WriteLine("No grades were entered") 112 End If 113 End Sub ' DisplayGradeReport 114 End Class ' GradeBook
Fig. 6.9 | GradeBook class uses Select…Case statement to countA, B, C, D and F grades. (Part 6 of 6.)
2009 Pearson Education, Inc. All rights reserved.
34
6.5 GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)Case Multiple Selection Statement (Cont.)Select Case grade
l• The expression following the keywords SelectCase is called the controlling expression.
• If a matching Case is found for the controlling i h d i h C hexpression, the code in that Case executes, then
program control proceeds to the first statement after the Select Case statementthe Select…Case statement.
2009 Pearson Education, Inc. All rights reserved.
35
6.5 GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)Case Multiple Selection Statement (Cont.)Common Programming Error 6.3D li t C t t t l i At tiDuplicate Case statements are logic errors. At run time,the first matching Case is executed.
Common Programming Error 6.4Common Programming Error 6.4If the value on the left side of the To keyword in a Case statement is larger than the value on the right side, the Case is ignored.
2009 Pearson Education, Inc. All rights reserved.
36
6.5 GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)• If no match occurs between the controlling
expression’s value and a Case label the optional
Case Multiple Selection Statement (Cont.)
expression s value and a Case label, the optional Case Else executes.
• Case Else must be the last Case• Case Else must be the last Case.
• Case statements can use relational operators• Case statements can use relational operators.Case Is < 0
• Multiple values can be tested in a Case statement:• Multiple values can be tested in a Case statement:Case 0, 5 To 9
• The controlling expression also may be a String or
2009 Pearson Education, Inc. All rights reserved.
The controlling expression also may be a String or Object.
37
6.5 GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)Case Multiple Selection Statement (Cont.)Error-Prevention Tip 6.4 P id C El i S l t C t t t CProvide a Case Else in Select...Case statements. Cases not handled in a Select...Case statement are ignored unless a Case Else is provided. The inclusion of a CaseElse statement can facilitate the processing of exceptional conditions.
2009 Pearson Education, Inc. All rights reserved.
38Outline
• Module GradeBookTest (Fig. 6.10) outputs a report based on the grades entered
1 ' Fig. 6.10: GradeBookTest.vb
GradeBookTest.vb
( 1 of 2 )
based on the grades entered.
1 Fig. 6.10: GradeBookTest.vb
2 ' Create GradeBook object, input grades and display grade report.
3 Module GradeBookTest
4 Sub Main()
5 ' create GradeBook object gradeBook1 and
6 ' t t t 6 ' pass course name to constructor
7 Dim gradeBook1 As New GradeBook("CS101 Introduction to VB")
8 9 gradeBook1.DisplayMessage() ' display welcome message
10 gradeBook1.InputGrades() ' read grades from user 11 gradeBook1.DisplayGradeReport() ' display report based on grades 12 End Sub ' Main 13 End Module ' GradeBookTest
Fig 6 10 | GradeBookTest creates a GradeBook object and invokesFig. 6.10 | GradeBookTest creates a GradeBook object and invokesits methods. (Part 1 of 2.)
2009 Pearson Education, Inc. All rights reserved.
39
Welcome to the grade book for
CS101 Introduction to VB!
Outline
CS101 Introduction to VB!
Enter a grade in the range 0-100, negative value to quit: 99
Enter a grade in the range 0-100, negative value to quit: 92
Enter a grade in the range 0-100, negative value to quit: 45
Enter a grade in the range 0-100, negative value to quit: 57
d i h 0 100 i l i 63
GradeBookTest.vb
( 2 of 2 )Enter a grade in the range 0-100, negative value to quit: 63
Enter a grade in the range 0-100, negative value to quit: 71
Enter a grade in the range 0-100, negative value to quit: 76
Enter a grade in the range 0-100, negative value to quit: 85
Enter a grade in the range 0-100, negative value to quit: 90
Enter a grade in the range 0-100, negative value to quit: 100 g g , g q
Enter a grade in the range 0-100, negative value to quit: -1
Grade Report:
Total of the 10 grades entered is 778
Class average is 77.80
Number of students who received each grade: Number of students who received each grade:
A: 4
B: 1
C: 2
D: 1
F: 2
Number of students who received a perfect score: 1
Fig. 6.10 | GradeBookTest creates a GradeBook object and invokes
2009 Pearson Education, Inc. All rights reserved.
g | jits methods. (Part 2 of 2.)
40
6.5 GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)Case Multiple Selection Statement (Cont.)• Methods declared Private can be called only by
other members of the class in hich the Privateother members of the class in which the Privatemethods are declared.
• Such Private methods are commonly referred to as• Such Private methods are commonly referred to as utility methods or helper methods.
2009 Pearson Education, Inc. All rights reserved.
41
6.5 GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)Case Multiple Selection Statement (Cont.)• The With statement allows you to make multiple
references to the same objectreferences to the same object.With gradeBook1
.DisplayMessage() ' display welcome messageI tG d () ' d d f .InputGrades() ' read grades from user
.DisplayGradeReport() ' display report based on grades
End With
• These lines of code are collectively known as a With t t t bl kstatement block.
2009 Pearson Education, Inc. All rights reserved.
42
6.5 GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)Case Multiple Selection Statement (Cont.)
• Figure 6.11 shows the UML activity diagram for the general Select...Case statement.
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.11 | Select…Case multiple-selection statement UML activity diagram.
43Outline
• The Do...Loop While repetition statement is similar to the While statement
DoLoopWhile.vb
( 1 of 2 )
to the While statement.• The program in Fig. 6.12 uses a Do...Loop While
statement to output the values 1–5. 1 ' Fig. 6.12: DoLoopWhile.vb
2 ' Demonstrating the Do...Loop While repetition statement.
3 Module DoLoopWhile
4 Sub Main()
5 Dim counter As Integer 1 5 Dim counter As Integer = 1
6 7 ' print values 1 to 5
8 Do
9 Console.Write("{0} ", counter)
10 counter += 1 11 Loop While counter <= 5 12 13 Console.WriteLine() 14 End Sub ' Main
Condition tested after loop body executes
15 End Module ' DoLoopWhile
1 2 3 4 5
hil
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.12 | Do…Loop While repetition statement.
44Outline
DoLoopWhile.vb
( 2 of 2 )
Error-Prevention Tip 6.5 .Infinite loops occur when the loop-continuation p pcondition in a While, Do While...Loop orDo...Loop While statement never becomes false.
2009 Pearson Education, Inc. All rights reserved.
45
6.6 Do…Loop While Repetition Statement (Cont.)(Cont.)
• The Do…Loop While UML activity diagram (Fig. 6.13) illustrates th t th l ti ti diti i t l t d til ft ththat the loop-continuation condition is not evaluated until after the statement body.
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.13 | Do…Loop While repetition statement activity diagram.
46Outline
• Figure 6.14 uses a Do...Loop Until statement to print the numbers from 1 to 5
1 ' Fig. 6.14: DoLoopUntil.vb
DoLoopUntil.vb
print the numbers from 1 to 5.
2 ' Using Do...Loop Until repetition statement.
3 Module DoLoopUntil
4 Sub Main()
5 Dim counter As Integer = 1
6 7 ' print values 1 to 5
8 Do
9 Console.Write("{0} ", counter)
10 counter += 1 11 Loop Until counter > 5
Condition tested after loop body executes
12 13 Console.WriteLine() 14 End Sub ' Main 15 End Module ' DoLoopUntil
loop body executes
1 2 3 4 5
Fig. 6.14 | Do…Loop Until repetition statement.
2009 Pearson Education, Inc. All rights reserved.
47
6.7 Do...Loop Until Repetition Statement (Cont.)(Cont.) Common Programming Error 6.5I l di i t l ti l t i tIncluding an incorrect relational operator or an incorrectfinal value for a loop counter in the condition of any repetition statement can cause off-by-one errors.y
Error-Prevention Tip 6.6.Infinite loops occur when the loop-termination condition in a Do Until...Loop or Do...Loop Until statement never b tbecomes true.
2009 Pearson Education, Inc. All rights reserved.
48
6.7 Do...Loop Until Repetition Statement (Cont.)(Cont.) Error-Prevention Tip 6.7 I t t ll d l th t th t l i bl iIn a counter-controlled loop, ensure that the control variable is incremented (or decremented) appropriately in the body of the loop to avoid an infinite loop.p p
2009 Pearson Education, Inc. All rights reserved.
49
6.8 Using Exit in Repetition Statements
• An Exit statement causes the program to exit immediately from a repetition statementimmediately from a repetition statement.
– The Exit Do statement can be executed in any Do statement.– Exit For and Exit While cause immediate exit fromExit For and Exit While cause immediate exit from For…Next and While…End While loops.
• These statements are used to alter a program’s flow of control.
2009 Pearson Education, Inc. All rights reserved.
50Outline
• Figure 6.15 demonstrates Exit statements.
1 ' Fig. 6.15: ExitTest.vb
2 ' Using the Exit statement in repetition statements.
3 Module ExitTest
ExitTest.vb
( 1 of 3 )
4 Sub Main()
5 Dim counter As Integer ' loop counter
6 7 ' exit For...Next statement
8 For counter = 1 To 10 8 For counter = 1 To 10
9 ' skip remaining code in loop only if counter = 5
10 If counter = 5 Then 11 Exit For ' break out of loop 12 End If 1313 14 Console.Write("{0} ", counter) ' output counter 15 Next 16
Fig. 6.15 | Exit statement in repetition statements. (Part 1 of 3.)
2009 Pearson Education, Inc. All rights reserved.
51Outline
17 Console.WriteLine(vbNewLine & _ 18 "Broke out of For...Next at counter = " & counter & vbNewLine) 19 counter = 1 ' reset counter 20 21 ' i il
ExitTest.vb
( 2 of 3 )21 ' exit Do Until...Loop statement 22 Do Until counter > 10 23 ' skip remaining code in loop only if counter = 5 24 If counter = 5 Then 25 Exit Do ' break out of loop 26 End If 27 28 Console.Write("{0} ", counter) ' output counter 29 counter += 1 ' increment counter 30 Loop 30 Loop 31 32 Console.WriteLine(vbNewLine & "Broke out of Do Until...Loop " & _ 33 " at counter = " & counter & vbNewLine) 34 counter = 1 ' reset counter 3535 36 ' exit While statement
Fig. 6.15 | Exit statement in repetition statements. (Part 2 of 3.)
2009 Pearson Education, Inc. All rights reserved.
52Outline
37 While counter <= 10 38 ' skip remaining code in loop only if counter = 5 39 If counter = 5 Then 40 Exit While ' break out of loop 41 End If
ExitTest.vb
( 3 of 3 )
42 43 Console.Write("{0} ", counter) ' output counter 44 counter += 1 ' increment counter 45 End While 4646 47 Console.WriteLine( _ 48 vbNewLine & "Broke out of While at counter = " & counter) 49 End Sub ' Main 50 End Module ' ExitTest
1 2 3 4
Broke out of For...Next at counter = 5
1 2 3 4
Broke out of Do Until Loop at counter = 5 Broke out of Do Until...Loop at counter = 5
1 2 3 4
Broke out of While at counter = 5
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.15 | Exit statement in repetition statements. (Part 3 of 3.)
536.9 Using Continue in Repetition Statements
• The Continue statement skips to the next iteration of the loopof the loop.
– The Continue Do statement can be executed in any Dostatement.
– Continue For and Continue While are used inFor... Next and While loops.
Continue For i t th t l i bl b• Continue For increments the control variable by the Step value.
2009 Pearson Education, Inc. All rights reserved.
54Outline
• Figure 6.16 demonstrates the Continue statements.
1 ' Fig. 6.16: ContinueTest.vb
2 ' Using the Continue statement in repetition statements.
3 Module ContinueTest
ContinueTest.vb
( 1 of 3 )
4 Sub Main()
5 Dim counter As Integer ' loop counter
6 7 ' skipping an iteration of a For...Next statement
8 For counter = 1 To 10 8 For counter = 1 To 10
9 If counter = 5 Then
10 Continue For ' skip to next iteration of loop if counter = 5 11 End If 12
l i ("{ } " ) '13 Console.Write("{0} ", counter) ' output counter 14 Next 15 16 Console.WriteLine(vbNewLine & _ 17 "Skipped printing in For...Next at counter = 5" & vbNewLine) 18 counter = 0 ' reset counter 19
Fig. 6.16 | Continue statement in repetition statements. (Part 1 of 3.)
2009 Pearson Education, Inc. All rights reserved.
55Outline
20 ' skipping an iteration of a Do Until...Loop statement 21 Do Until counter >= 10 22 counter += 1 ' increment counter 23 24 f 5 h
ContinueTest.vb
( 2 of 3 )24 If counter = 5 Then 25 Continue Do ' skip to next iteration of loop if counter = 5 26 End If 27 28 Console.Write("{0} ", counter) ' output counter 29 Loop 30 31 Console.WriteLine(vbNewLine & _ 32 "Skipped printing in Do Until...Loop at counter = 5" & vbNewLine) 33 counter = 0 ' reset counter 33 counter = 0 reset counter
34 35 ' skipping an iteration of a While statement 36 While counter < 10 37 counter += 1 ' increment counter 3838 39 If counter = 5 Then 40 Continue While ' skip to next iteration of loop if counter = 5 41 End If
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.16 | Continue statement in repetition statements. (Part 2 of 3.)
56Outline
42 43 Console.Write("{0} ", counter) ' output counter 44 End While
ContinueTest.vb
( 3 of 3 )
45 46 Console.WriteLine( _ 47 vbNewLine & "Skipped printing in While at counter = 5") 48 End Sub ' Main 49 End Module ' ContinueTest 49 End Module ContinueTest
1 2 3 4 6 7 8 9 10
Skipped printing in For...Next at counter = 5
1 2 3 4 6 7 8 9 10
Skipped printing in Do Until...Loop at counter = 5
1 2 3 4 6 7 8 9 10
Skipped printing in While at counter = 5
Fig. 6.16 | Continue statement in repetition statements. (Part 3 of 3.)
2009 Pearson Education, Inc. All rights reserved.
57
6.10 Logical Operators • The logical And operator can be used as follows:If gender = "F" And age >= 65 Then
seniorFemales += 1
End If
• The If Then statement considers the combined condition:• The If Then statement considers the combined condition:gender = "F" And age >= 65
• Figure 6.17 is a truth table for the And operator. expression1 expression2 expression1 And expression2
False False False
g p
False True False
True False False
True True True
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.17 | Truth table for the logical And operator.
58
6.10 Logical Operators (Cont.)
Logical Or Operatorh O i d i h f ll i• The Or operator is used in the following segment:
If (semesterAverage >= 90 Or finalExam >= 90) Then Console.WriteLine("Student grade is A")
End If
• Figure 6.18 provides a truth table for the Or operator.
expression1 expression2 expression1 Or expression2
False False False
False True True False True True
True False True
True True True
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.18 | Truth table for the logical Or operator.
59
6.10 Logical Operators (Cont.)
Logical AndAlso and OrElse Operators• AndAlso and OrElse are similar to the And and Or• AndAlso and OrElse are similar to the And and Or
operators.(gender = "F" AndAlso age >= 65)(gender F AndAlso age > 65)
• The preceding expression stops evaluation immediately if gender is not equal to "F"; this is called short-circuit
l tievaluation.Performance Tip 6.2In expressions using operator AndAlso if the separate conditions areIn expressions using operator AndAlso, if the separate conditions are independent of one an-other, place the condition most likely to be false as the leftmost condition. In expres-sions using operator OrElse, make the condition most likely to be true the leftmost condition. Each of these
2009 Pearson Education, Inc. All rights reserved.
condition most likely to be true the leftmost condition. Each of these suggestions can reduce a program’s execution time.
60
6.10 Logical Operators (Cont.)
• AndAlso and OrElse operators can be used in place of Andand Orand Or.
• An exception to this rule occurs when the right operand of a condition produces a side effect:
Console.WriteLine("How old are you?")
If (gender = "F" And Console.ReadLine() >= 65) Then(g () )Console.WriteLine("You are a female senior citizen.")
End If
Error-Prevention Tip 6.8Avoid expressions with side effects in conditions,
2009 Pearson Education, Inc. All rights reserved.
because side effects often cause subtle errors.
61
6.10 Logical Operators (Cont.)
Logical Xor OperatorA di i i i h l i l l i OR ( )• A condition containing the logical exclusive OR (Xor)operator is true if and only if one of its operands results in a true value and the other results in a false value.
• Figure 6.19 presents a truth table for the Xor operator.
expression1 expression2 expression1 Xor expression2
False False False
False True True False True True
True False True
True True False
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.19 | Truth table for the logical exclusive OR (Xor) operator.
62
6.10 Logical Operators (Cont.)
Logical Not OperatorTh N t bl “ ” h• The Not operator enables you to “reverse” the meaning of a condition.Th l i l ti t i t• The logical negation operator is a unary operator, requiring only one operand.
If Not (grade = sentinelValue) ThenIf Not (grade = sentinelValue) ThenConsole.WriteLine("The next grade is " & grade)
End If
• The parentheses are necessary because Not has a higher precedence than the equality operator.
2009 Pearson Education, Inc. All rights reserved.
63
6.10 Logical Operators (Cont.)
• You can avoid using Not by expressing the condition differently:differently:
If grade <> sentinelValue Then
Console.WriteLine("The next grade is " & grade)
End If
• Figure 6.20 provides a truth table for Not.
expression Not expression
False True
Fig. 6.20 | Truth table for operator Not (logical negation).
True False
2009 Pearson Education, Inc. All rights reserved.
64Outline• Figure 6.21 demonstrates the logical operators by
displaying their truth tables.
1 ' Fig. 6.21: LogicalOperators.vb
2 ' Using logical operators.
3 Module LogicalOperators
LogicalOperators.vb
( 1 of 4 ) 4 Sub Main()
5 ' display truth table for And
6 Console.WriteLine("And" & vbNewLine & _
7 "False And False: " & (False And False) & vbNewLine & _
8 "False And True: " & (False And True) & vbNewLine &
( 1 of 4 )
8 False And True: & (False And True) & vbNewLine & _
9 "True And False: " & (True And False) & vbNewLine & _
10 "True And True: " & (True And True) & vbNewLine) 11 12 ' display truth table for Or 13 l i i (" " & b i & 13 Console.WriteLine("Or" & vbNewLine & _ 14 "False Or False: " & (False Or False) & vbNewLine & _ 15 "False Or True: " & (False Or True) & vbNewLine & _ 16 "True Or False: " & (True Or False) & vbNewLine & _ 17 "True Or True: " & (True Or True) & vbNewLine) 18
Fig. 6.21 | Logical operator truth tables. (Part 1 of 4.)
2009 Pearson Education, Inc. All rights reserved.
65Outline
19 ' display truth table for AndAlso 20 Console.WriteLine("AndAlso" & vbNewLine & _ 21 "False AndAlso False: " & (False AndAlso False) & vbNewLine & _ 22 "False AndAlso True: " & (False AndAlso True) & vbNewLine &
LogicalOperators.vb
( 2 of 4 )22 False AndAlso True: & (False AndAlso True) & vbNewLine & _
23 "True AndAlso False: " & (True AndAlso False) & vbNewLine & _ 24 "True AndAlso True: " & (True AndAlso True) & vbNewLine) 25 26 ' display truth table for OrElse
( 2 of 4 )
27 Console.WriteLine("OrElse" & vbNewLine & _ 28 "False OrElse False: " & (False OrElse False) & vbNewLine & _ 29 "False OrElse True: " & (False OrElse True) & vbNewLine & _ 30 "True OrElse False: " & (True OrElse False) & vbNewLine & _ 31 "True OrElse True: " & (True OrElse True) & vbNewLine) ( ) )
32 33 ' display truth table for Xor 34 Console.WriteLine("Xor" & vbNewLine & _ 35 "False Xor False: " & (False Xor False) & vbNewLine & _ 36 "False Xor True: " & (False Xor True) & vbNewLine & 36 False Xor True: & (False Xor True) & vbNewLine & _
37 "True Xor False: " & (True Xor False) & vbNewLine & _ 38 "True Xor True: " & (True Xor True) & vbNewLine)
Fig. 6.21 | Logical operator truth tables. (Part 2 of 4.)
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.21 | Logical operator truth tables. (Part 2 of 4.)
66Outline
39 40 ' display truth table for Not 41 Console.WriteLine("Not" & vbNewLine & "Not False: " & _ 42 (Not False) & vbNewLine & "Not True: " & (Not True) & vbNewLine) 43 End Sub ' Main
LogicalOperators.vb
( 3 of 4 )44 End Module ' LogicalOperators
And
False And False: False
False And True: False
( 3 of 4 )
True And False: False
True And True: True
Or
False Or False: False
False Or True: True False Or True: True
True Or False: True
True Or True: True
AndAlso
False AndAlso False: False False AndAlso False: False
False AndAlso True: False
True AndAlso False: False
True AndAlso True: True
(continued on next page...)
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.21 | Logical operator truth tables. (Part 3 of 4.)
67Outline
(continued from previous page…) And
False And False: False
False And True: False
T A d F l F l
LogicalOperators.vb
( 4 of 4 )True And False: False
True And True: True
Or
False Or False: False
False Or True: True
( 4 of 4 )
False Or True: True
True Or False: True
True Or True: True
AndAlso
False AndAlso False: False
False AndAlso True: False
True AndAlso False: False
True AndAlso True: True
Fig. 6.21 | Logical operator truth tables. (Part 4 of 4.)
2009 Pearson Education, Inc. All rights reserved.
68
6.10 Logical Operators (Cont.)
• Figure 6.22 displays the operators in decreasing orderof precedenceof precedence.
Operators Type
^ exponentiation
+ - unary plus and minus
* / multiplicative operatorsp p
\ integer division
Mod modulus
+ - additive operators
Fig. 6.22 | Precedence of the operators discussed so far. (Part 1 of 2.)
additive operators
2009 Pearson Education, Inc. All rights reserved.
69
6.10 Logical Operators (Cont.)
Operators Type
& concatenation
< <= > >= = <> relational and equality < <= > >= = <> relational and equality
Not logical NOT
And AndAlso logical AND
Or OrElse logical inclusive OR Or OrElse logical inclusive OR
Xor logical exclusive OR
= += -= *= /= \= ^= &= assignment
Fig. 6.22 | Precedence of the operators discussed so far. (Part 2 of 2.)
2009 Pearson Education, Inc. All rights reserved.
70
6.11 Software Engineering Case Study: Identifying Objects’ States and ActivitiesIdentifying Objects States and Activities in the ATM System
E h bj t i t th h i f di t• Each object in a system goes through a series of discrete states.
• State machine diagrams model key states of an objectState machine diagrams model key states of an object and show under what circumstances the object changes state.
• Figure 6.23 models some of the states of an ATM object.
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.23 | State machine diagram for some of the states of the ATM object.
71
6.11 Software Engineering Case Study: Identifying Objects’ States and ActivitiesIdentifying Objects States and Activities in the ATM System (Cont.)
• An activity diagram models an object’s workflow• An activity diagram models an object’s workflow.• The activity diagram in Fig. 6.24 models the actions involved
in executing a BalanceInquiry transaction.g q y
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.24 | Activity diagram for a BalanceInquiry transaction.
72
6.11 Software Engineering Case Study: Identifying Objects’ States and Activities in the ATM System (Cont.)
• Figure 6 25 shows a moreFigure 6.25 shows a more complex activity diagram for a Withdrawal.
2009 Pearson Education, Inc. All rights reserved.
Fig. 6.25 | Activity diagram for a Withdrawal transaction.