+ All Categories
Home > Documents > 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

Date post: 13-Jan-2016
Category:
Upload: gabriel-allison
View: 216 times
Download: 0 times
Share this document with a friend
72
2009 Pearson Education, Inc. All rights rese 1 6 Control Statements: Part 2
Transcript
Page 1: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

1

66

Control Statements: Part 2

Page 2: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

2

Who can control his fate?– William Shakespeare, Othello

The used key is always bright.– Benjamin Franklin

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.

– Demosthenes

Page 3: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

3

OBJECTIVES

In this chapter you will learn: The essentials of counter-controlled repetition. To use the For…Next, Do…Loop While andDo…Loop Until repetition statements to execute statements in a program repeatedly.

To perform multiple selection using theSelect…Case selection statement.

Page 4: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

4

OBJECTIVES

To use the Exit statement to break out of a repetition statement.

To use the Continue statement to break outof the current iteration of a repetition statement.

To use logical operators to form more complex conditions.

Page 5: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

5

6.1   Introduction

6.2   Essentials of Counter-Controlled Repetition

6.3   For…Next Repetition Statement

6.4   Examples Using the For…Next Statement

6.5   GradeBook Case Study: Select…CaseMultiple-Selection Statement

6.6   Do…Loop While Repetition Statement

6.7   Do…Loop Until Repetition Statement

6.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

Page 6: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

6

6.2  Essentials of Counter-Controlled Repetition

• Counter-controlled repetition requires– the name of the control variable

– the initial value

– the increment (or decrement) value

– the condition that tests for the final value

Page 7: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

7

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

7 While counter <= 10 ' test final value of loop counter

8 Console.Write("{0} ", counter)

9 counter += 2 ' increment counter

10 End While

11

12 Console.WriteLine()

13 End Sub ' Main

14 End Module ' WhileCounter 2 4 6 8 10

Outline

WhileCounter.vb

• The example in Fig. 6.1 uses counter-controlled repetition to display the even integers in the range 2–10.

Initializing counterbefore the loop

Fig. 6.1 | Counter-controlled repetition with the While…End While statement.

Page 8: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

8

1 ' Fig. 6.2: ForCounter.vb

2 ' Using the For...Next statement for counter-controlled repetition.

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)

9 Next

10

11 Console.WriteLine()

12 End Sub ' Main

13 End Module ' ForCounter 2 4 6 8 10

Outline

ForCounter.vb

( 1 of 2 )

• In this For...Next statement, counter (Fig. 6.2) is used to print even numbers from 2 to 10.

Good Programming Practice 6.1Place a blank line before and after each control statement to make it stand out in the program.

Fig. 6.2 | Counter-controlled repetition with the For…Next statement.

Page 9: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

9

Outline

ForCounter.vb

( 2 of 2 )

Good Programming Practice 6.2Vertical spacing above and below control statements, as well as indentation of the bodies of control statements, gives programs atwo-dimensional appearance that enhances readability.

Error-Prevention Tip 6.1 Use 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 iteration than is necessary) tend to disappear, because the terminating value is clear.

Page 10: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

10

6.3  For…Next Repetition Statement (Cont.)

• The first line of the For…Next statement sometimes is called the For…Next header (Fig. 6.3).

Fig. 6.3 | For...Next header components.

Page 11: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

11

• The general form of the For…Next statement is For initialization To finalValue Step increment

statement

Next

• A For…Next statement can be represented byan equivalent While statement:

initialization

While variable <= finalValue statement increment

End While

6.3  For…Next Repetition Statement (Cont.)

Page 12: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

12

• The counter variable may be declared before theFor…Next statement:

Dim counter As Integer

For 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.

6.3  For…Next Repetition Statement (Cont.)

Page 13: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

13

6.3  For…Next Repetition Statement (Cont.)

Common Programming Error 6.1Counter-controlled loops should not be controlledwith floating-point variables. Floating-point values are represented only approximately in the computer’s memory; this can lead to imprecise counter values and inaccurate tests for termination.

Page 14: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

14

6.3  For…Next Repetition Statement (Cont.)

Error-Prevention Tip 6.2

Although 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.

Common Programming Error 6.2

In nested For…Next loops, the use of the samecontrol-variable name in more than one loop is acompilation error.

Page 15: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

15

For counter As Integer = 1 To 10 Step 2

• The activity diagram for a For…Next statement (Fig. 6.4) is similar to a While statement.

Fig. 6.4 | For...Next repetition statement activity diagram.

6.3  For…Next Repetition Statement (Cont.)

Page 16: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

16

• Local type inference infers a local variable’s typebased on the context of initialization.

Dim x = 7

• The compiler infers type Integer.

Dim y = -123.45

• The compiler infers type Double.

6.3  For… Next Repetition Statement (Cont.)

Page 17: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

17

For counter As Integer = 1 To 10

• The preceding For Next header can now be written as:For counter = 1 To 10

• In this case, counter is of type Integer becauseit is initialized with a whole number (1).

• Local type inference can be used on any variablethat is initialized in its declaration.

6.3  For… Next Repetition Statement (Cont.)

Page 18: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

18

1 ' Fig. 6.5: Sum.vb

2 ' Using For...Next statement to demonstrate summation.

3 Imports System.Windows.Forms

4

5 Module Sum

6 Sub Main()

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)

17 End Sub ' Main

18 End Module ' Sum

Outline• The program in Fig. 6.5 uses a For...Next statementto sum the even integers from 2 to 100.

• Remember to add a reference to System.Windows.Forms.dll.

Method MessageBox.Show can take four arguments.

Sum.vb

( 1 of 2 )

Fig. 6.5 | For…Next statement used for summation. (Part 1 of 2.)

Page 19: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

19

Outline

Sum.vb

( 2 of 2 )

Message text

Title bar text

MessageBoxIcon.Information

MessageBoxButtons.OK

Fig. 6.5 | For…Next statement used for summation. (Part 2 of 2.)

Page 20: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

20

6.4  Examples Using the For Next Statement (Cont.)

• Method MessageBox.Show can take four arguments.– The first two arguments are the text and title bar.

– The third argument indicates which button(s) to display.

– The fourth argument indicates which icon appears.

Page 21: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

21

6.4  Examples Using the For Next Statement (Cont.)

Fig. 6.6 | Message dialog icon constants.

MessageBoxIcon constants Icon Description

MessageBoxIcon.Warning or MessageBoxIcon.Exclamation

Used to caution the user against potential problems.

MessageBoxIcon.Information Used to display information about the state of the application.

MessageBoxIcon.None No icon is displayed.

MessageBoxIcon.Error Used to alert the user to errors or critical situations.

Page 22: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

22

6.4  Examples Using the For Next Statement (Cont.)

Fig. 6.7 | Message dialog button constants. (Part 1 of 2.)

MessageBoxButton constants Description

MessageBoxButtons.OK 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.

MessageBoxButtons.YesNo Yes and No buttons. Allow the user to respond to a question.

Page 23: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

23

6.4  Examples Using the For Next Statement (Cont.)

MessageBoxButton constants Description

MessageBoxButtons.YesNoCancel 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.

MessageBoxButtons.AbortRetryIgnore Abort, Retry and I gnore 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 the failed operation and continue.

Fig. 6.7 | Message dialog button constants. (Part 2 of 2.)

Page 24: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

24

• Consider the following problem statement:

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 of 10 years. Use the following formula:

a = p (1 + r) n

6.4  Examples Using the For Next Statement (Cont.)

Page 25: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

25

1 ' Fig. 6.8: Interest.vb

2 ' Calculating compound interest.

3 Imports System.Windows.Forms

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

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

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) _

19 & vbNewLine

20 Next

21

22 ' display output

23 MessageBox.Show(output, "Compound Interest", _

24 MessageBoxButtons.OK, MessageBoxIcon.Information)

25 End Sub ' Main

26 End Module ' Interest

Outline

Interest.vb

( 1 of 3 )

amount and principal are declared as type Decimal

Calculating interest foreach year

String.Format formats text as directed

Fig. 6.8 | For…Next statement used to calculatecompound interest. (Part 1 of 2.)

Page 26: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

26

Outline

Interest.vb

( 2 of 3 )

Fig. 6.8 | For…Next statement used to calculatecompound interest. (Part 2 of 2.)

Page 27: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

27

Outline

Interest.vb

( 3 of 3 )

Error-Prevention Tip 6.3

Do not use variables of type Single or Double to perform precise monetary calculations. The imprecision of floating-point numbers can cause errors that result in incorrect monetary values. Use the type Decimal for monetary calculations.

Performance Tip 6.1

Avoid 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 and prior to the loop.

Page 28: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

28

1 ' Fig. 6.9: GradeBook.vb

2 ' GradeBook class uses Select...Case statement to count letter grades.

3 Public Class GradeBook

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

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

13

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

Outline

GradeBook.vb

( 1 of 6 )

• The GradeBook class now uses the Select...Case multiple-selection statement (Fig. 6.9).

Fig. 6.9 | GradeBook class uses Select…Case statement to countA, B, C, D and F grades. (Part 1 of 6.)

Page 29: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

29

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

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)

34

35 Console.WriteLine( _

36 "Course name (" & value & ") exceeds maximum length (25).")

37 Console.WriteLine( _

38 "Limiting course name to first 25 characters." & vbNewLine)

39 End If

40 End Set

41 End Property ' CourseName

Outline

GradeBook.vb

( 2 of 6 )

Fig. 6.9 | GradeBook class uses Select…Case statement to countA, B, C, D and F grades. (Part 2 of 6.)

Page 30: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

30

42

43 ' display a welcome message to the GradeBook user

44 Public Sub DisplayMessage()

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

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

54

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

Outline

GradeBook.vb

( 3 of 6 )

Fig. 6.9 | GradeBook class uses Select…Case statement to countA, B, C, D and F grades. (Part 3 of 6.)

Page 31: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

31

60 ' call method to increment appropriate counter

61 IncrementLetterGradeCounter(grade)

62

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

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

Outline

GradeBook.vb

( 4 of 6 )

Using a Select...Case statement to determine which counter to increment.

Fig. 6.9 | GradeBook class uses Select…Case statement to countA, B, C, D and F grades. (Part 4 of 6.)

Page 32: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

32

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

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()

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

96 Dim average As Double = total / gradeCounter

Outline

GradeBook.vb

( 5 of 6 )

Fig. 6.9 | GradeBook class uses Select…Case statement to countA, B, C, D and F grades. (Part 5 of 6.)

Page 33: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

33

97

98 ' output summary of results

99 Console.WriteLine("Total of the {0} grades entered is {1}", _

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

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 "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

Outline

GradeBook.vb

( 6 of 6 )

Fig. 6.9 | GradeBook class uses Select…Case statement to countA, B, C, D and F grades. (Part 6 of 6.)

Page 34: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

34

6.5  GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)

Select Case grade• The expression following the keywords Select Case is called the controlling expression.

• If a matching Case is found for the controlling expression, the code in that Case executes, then program control proceeds to the first statement after the Select…Case statement.

Page 35: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

35

6.5  GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)

Common Programming Error 6.3Duplicate Case statements are logic errors. At run time,the first matching Case is executed.

Common 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.

Page 36: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

36

• If no match occurs between the controlling expression’s value and a Case label, the optional Case Else executes.

• Case Else must be the last Case.

• Case statements can use relational operators.Case Is < 0

• Multiple values can be tested in a Case statement:Case 0, 5 To 9

• The controlling expression also may be a String or Object.

6.5  GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)

Page 37: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

37

6.5  GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)

Error-Prevention Tip 6.4 Provide 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 Case Else statement can facilitate the processing of exceptional conditions.

Page 38: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

38

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 ' 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

Outline

GradeBookTest.vb

( 1 of 2 )

• Module GradeBookTest (Fig. 6.10) outputs a report based on the grades entered.

Fig. 6.10 | GradeBookTest creates a GradeBook object and invokesits methods. (Part 1 of 2.)

Page 39: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

39

Welcome to the grade book for 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 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 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: A: 4 B: 1 C: 2 D: 1 F: 2 Number of students who received a perfect score: 1

Outline

GradeBookTest.vb

( 2 of 2 )

Fig. 6.10 | GradeBookTest creates a GradeBook object and invokesits methods. (Part 2 of 2.)

Page 40: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

40

6.5  GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)

• Methods declared Private can be called only by other members of the class in which the Private methods are declared.

• Such Private methods are commonly referred to as utility methods or helper methods.

Page 41: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

41

6.5  GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)

• The With statement allows you to make multiple references to the same object.

With gradeBook1 .DisplayMessage() ' display welcome message .InputGrades() ' read grades from user .DisplayGradeReport() ' display report based on grades

End With

• These lines of code are collectively known as a With statement block.

Page 42: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

42

Fig. 6.11 | Select…Case multiple-selection statement UML activity diagram.

6.5  GradeBook Case Study: Select… Case Multiple-Selection Statement (Cont.)

• Figure 6.11 shows the UML activity diagram for the general Select...Case statement.

Page 43: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

43

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

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

15 End Module ' DoLoopWhile 1 2 3 4 5

Outline

DoLoopWhile.vb

( 1 of 2 )

• The Do...Loop While repetition statement is similar to the While statement.

• The program in Fig. 6.12 uses a Do...Loop While statement to output the values 1–5.

Condition tested after loop body executes

Fig. 6.12 | Do…Loop While repetition statement.

Page 44: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

44

Outline

DoLoopWhile.vb

( 2 of 2 )

Error-Prevention Tip 6.5 .Infinite loops occur when the loop-continuation condition in a While, Do While...Loop orDo...Loop While statement never becomes false.

Page 45: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

45

6.6  Do…Loop While Repetition Statement (Cont.)

• The Do…Loop While UML activity diagram (Fig. 6.13) illustrates that the loop-continuation condition is not evaluated until after the statement body.

Fig. 6.13 | Do…Loop While repetition statement activity diagram.

Page 46: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

46

1 ' Fig. 6.14: DoLoopUntil.vb

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

12

13 Console.WriteLine()

14 End Sub ' Main

15 End Module ' DoLoopUntil 1 2 3 4 5

Outline

DoLoopUntil.vb

• Figure 6.14 uses a Do...Loop Until statement to print the numbers from 1 to 5.

Condition tested after loop body executes

Fig. 6.14 | Do…Loop Until repetition statement.

Page 47: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

47

6.7  Do...Loop Until Repetition Statement (Cont.)

Common Programming Error 6.5Including 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.

Error-Prevention Tip 6.6 .Infinite loops occur when the loop-termination condition in a Do Until...Loop or Do...Loop Until statement never becomes true.

Page 48: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

48

6.7  Do...Loop Until Repetition Statement (Cont.)

Error-Prevention Tip 6.7 In 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.

Page 49: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

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 statement.

– The Exit Do statement can be executed in any Do statement.

– Exit 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.

Page 50: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

50

1 ' Fig. 6.15: ExitTest.vb

2 ' Using the Exit statement in repetition statements.

3 Module ExitTest

4 Sub Main()

5 Dim counter As Integer ' loop counter

6

7 ' exit For...Next statement

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

13

14 Console.Write("{0} ", counter) ' output counter

15 Next

16

Outline

ExitTest.vb

( 1 of 3 )

• Figure 6.15 demonstrates Exit statements.

Fig. 6.15 | Exit statement in repetition statements. (Part 1 of 3.)

Page 51: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

51

17 Console.WriteLine(vbNewLine & _

18 "Broke out of For...Next at counter = " & counter & vbNewLine)

19 counter = 1 ' reset counter

20

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

31

32 Console.WriteLine(vbNewLine & "Broke out of Do Until...Loop " & _

33 " at counter = " & counter & vbNewLine)

34 counter = 1 ' reset counter

35

36 ' exit While statement

Outline

ExitTest.vb

( 2 of 3 )

Fig. 6.15 | Exit statement in repetition statements. (Part 2 of 3.)

Page 52: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

52

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

42

43 Console.Write("{0} ", counter) ' output counter

44 counter += 1 ' increment counter

45 End While

46

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 1 2 3 4 Broke out of While at counter = 5

Outline

ExitTest.vb

( 3 of 3 )

Fig. 6.15 | Exit statement in repetition statements. (Part 3 of 3.)

Page 53: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

53

6.9  Using Continue in Repetition Statements

• The Continue statement skips to the next iteration of the loop.

– The Continue Do statement can be executed in any Do statement.

– Continue For and Continue While are used inFor... Next and While loops.

• Continue For increments the control variable by the Step value.

Page 54: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

54

1 ' Fig. 6.16: ContinueTest.vb

2 ' Using the Continue statement in repetition statements.

3 Module ContinueTest

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

9 If counter = 5 Then

10 Continue For ' skip to next iteration of loop if counter = 5

11 End If

12

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

Outline

ContinueTest.vb

( 1 of 3 )

• Figure 6.16 demonstrates the Continue statements.

Fig. 6.16 | Continue statement in repetition statements. (Part 1 of 3.)

Page 55: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

55

20 ' skipping an iteration of a Do Until...Loop statement

21 Do Until counter >= 10

22 counter += 1 ' increment counter

23

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

34

35 ' skipping an iteration of a While statement

36 While counter < 10

37 counter += 1 ' increment counter

38

39 If counter = 5 Then

40 Continue While ' skip to next iteration of loop if counter = 5

41 End If

Outline

ContinueTest.vb

( 2 of 3 )

Fig. 6.16 | Continue statement in repetition statements. (Part 2 of 3.)

Page 56: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

56

42

43 Console.Write("{0} ", counter) ' output counter

44 End While

45

46 Console.WriteLine( _

47 vbNewLine & "Skipped printing in While at counter = 5")

48 End Sub ' Main

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

Outline

ContinueTest.vb

( 3 of 3 )

Fig. 6.16 | Continue statement in repetition statements. (Part 3 of 3.)

Page 57: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

57

6.10  Logical Operators

Fig. 6.17 | Truth table for the logical And operator.

expression1 expression2 expression1 And expression2

False False False

False True False

True False False

True True True

• 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:gender = "F" And age >= 65

• Figure 6.17 is a truth table for the And operator.

Page 58: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

58

6.10  Logical Operators (Cont.)

Fig. 6.18 | Truth table for the logical Or operator.

Logical Or Operator• 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

True False True

True True True

Page 59: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

59

Logical AndAlso and OrElse Operators

• AndAlso and OrElse are similar to the And and Or operators.

(gender = "F" AndAlso age >= 65)

• The preceding expression stops evaluation immediately if gender is not equal to "F"; this is called short-circuit evaluation.

6.10  Logical Operators (Cont.)

Performance Tip 6.2In 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 suggestions can reduce a program’s execution time.

Page 60: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

60

• AndAlso and OrElse operators can be used in place of And and 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 Console.WriteLine("You are a female senior citizen.")

End If

Error-Prevention Tip 6.8Avoid expressions with side effects in conditions,because side effects often cause subtle errors.

6.10  Logical Operators (Cont.)

Page 61: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

61

6.10  Logical Operators (Cont.)

Fig. 6.19 | Truth table for the logical exclusive OR (Xor) operator.

Logical Xor Operator• 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

True False True

True True False

Page 62: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

62

Logical Not Operator

• The Not operator enables you to “reverse” the meaning of a condition.

• The logical negation operator is a unary operator, requiring only one operand.

If Not (grade = sentinelValue) Then Console.WriteLine("The next grade is " & grade)

End If

• The parentheses are necessary because Not has a higher precedence than the equality operator.

6.10  Logical Operators (Cont.)

Page 63: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

63

6.10  Logical Operators (Cont.)

Fig. 6.20 | Truth table for operator Not (logical negation).

• You can avoid using Not by expressing the condition 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

True False

Page 64: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

64

1 ' Fig. 6.21: LogicalOperators.vb

2 ' Using logical operators.

3 Module LogicalOperators

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 & _

9 "True And False: " & (True And False) & vbNewLine & _

10 "True And True: " & (True And True) & vbNewLine)

11

12 ' display truth table for Or

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

Outline

LogicalOperators.vb

( 1 of 4 )

• Figure 6.21 demonstrates the logical operators by displaying their truth tables.

Fig. 6.21 | Logical operator truth tables. (Part 1 of 4.)

Page 65: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

65

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 & _

23 "True AndAlso False: " & (True AndAlso False) & vbNewLine & _

24 "True AndAlso True: " & (True AndAlso True) & vbNewLine)

25

26 ' display truth table for OrElse

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 & _

37 "True Xor False: " & (True Xor False) & vbNewLine & _

38 "True Xor True: " & (True Xor True) & vbNewLine)

Outline

LogicalOperators.vb

( 2 of 4 )

Fig. 6.21 | Logical operator truth tables. (Part 2 of 4.)

Page 66: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

66

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

44 End Module ' LogicalOperators And False And False: False False And True: False True And False: False True And True: True Or False Or False: False 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 (continued on next page...)

Outline

LogicalOperators.vb

( 3 of 4 )

Fig. 6.21 | Logical operator truth tables. (Part 3 of 4.)

Page 67: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

67

(continued from previous page…) And False And False: False False And True: False True And False: False True And True: True Or False Or False: False 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

Outline

LogicalOperators.vb

( 4 of 4 )

Fig. 6.21 | Logical operator truth tables. (Part 4 of 4.)

Page 68: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

68

6.10  Logical Operators (Cont.)

Fig. 6.22 | Precedence of the operators discussed so far. (Part 1 of 2.)

• Figure 6.22 displays the operators in decreasing orderof precedence.

Operators Type

^ exponentiation

+ - unary plus and minus

* / multiplicative operators

\ integer division

Mod modulus

+ - additive operators

Page 69: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

69

6.10  Logical Operators (Cont.)

Operators Type

& concatenation

< <= > >= = <> relational and equality

Not logical NOT

And AndAlso logical AND

Or OrElse logical inclusive OR

Xor logical exclusive OR

= += -= *= /= \= ^= &= assignment

Fig. 6.22 | Precedence of the operators discussed so far. (Part 2 of 2.)

Page 70: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

70

6.11   Software Engineering Case Study: Identifying Objects’ States and Activities in the ATM System

• Each object in a system goes through a series of discrete states.

• State 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.

Fig. 6.23 | State machine diagram for some of the states of the ATM object.

Page 71: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

71

6.11  Software Engineering Case Study: Identifying Objects’ States and Activities in the ATM System (Cont.)

• An activity diagram models an object’s workflow.

• The activity diagram in Fig. 6.24 models the actions involved in executing a BalanceInquiry transaction.

Fig. 6.24 | Activity diagram for a BalanceInquiry transaction.

Page 72: 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

2009 Pearson Education, Inc. All rights reserved.

72

6.11   Software Engineering Case Study: Identifying Objects’ States and Activities in the ATM System (Cont.)

Fig. 6.25 | Activity diagram for a Withdrawal transaction.

• Figure 6.25 shows a more complex activity diagram for a Withdrawal.


Recommended