Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: " 2009 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2."— Presentation transcript:

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

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 judged in the light of the final issue. – Demosthenes

3  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 and Do … Loop Until repetition statements to execute statements in a program repeatedly.  To perform multiple selection using the Select … Case selection statement.

4  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 out of the current iteration of a repetition statement.  To use logical operators to form more complex conditions.

5  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 … Case Multiple-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

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

7  2009 Pearson Education, Inc. All rights reserved. 7 Outline WhileCounter.vb The example in Fig. 6.1 uses counter-controlled repetition to display the even integers in the range 2–10. Initializing counter before the loop Fig. 6.1 | Counter-controlled repetition with the While … End While statement.

8  2009 Pearson Education, Inc. All rights reserved. 8 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.1 Place 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.

9  2009 Pearson Education, Inc. All rights reserved. 9 Outline ForCounter.vb ( 2 of 2 ) Good Programming Practice 6.2 Vertical spacing above and below control statements, as well as indentation of the bodies of control statements, gives programs a two-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.

10  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.

11  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 by an equivalent While statement: initialization While variable <= finalValue statement increment End While 6.3 For…Next Repetition Statement (Cont.)

12  2009 Pearson Education, Inc. All rights reserved. 12 The counter variable may be declared before the For … Next statement: Dim counter As Integer For counter = 2 To 10 Step 2 Console.Write("{0} ", counter) Next Values of a For … Next statement header may contain 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.)

13  2009 Pearson Education, Inc. All rights reserved. 13 6.3 For…Next Repetition Statement (Cont.) Common Programming Error 6.1 Counter-controlled loops should not be controlled with 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.

14  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 be changed in the body of a For … Next loop, avoid doing so, because this practice can lead to subtle errors. Common Programming Error 6.2 In nested For … Next loops, the use of the same control-variable name in more than one loop is a compilation error.

15  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.)

16  2009 Pearson Education, Inc. All rights reserved. 16 Local type inference infers a local variable ’ s type based 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.)

17  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 because it is initialized with a whole number ( 1 ). Local type inference can be used on any variable that is initialized in its declaration. 6.3 For… Next Repetition Statement (Cont.)

18  2009 Pearson Education, Inc. All rights reserved. 18 Outline The program in Fig. 6.5 uses a For... Next statement to 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.)

19  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.)

20  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.

21  2009 Pearson Education, Inc. All rights reserved. 21 6.4 Examples Using the For Next Statement (Cont.) Fig. 6.6 | Message dialog icon constants.

22  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.)

23  2009 Pearson Education, Inc. All rights reserved. 23 6.4 Examples Using the For Next Statement (Cont.) Fig. 6.7 | Message dialog button constants. (Part 2 of 2.)

24  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.)

25  2009 Pearson Education, Inc. All rights reserved. 25 Outline Interest.vb ( 1 of 3 ) amount and principal are declared as type Decimal Calculating interest for each year String.Format formats text as directed Fig. 6.8 | For … Next statement used to calculate compound interest. (Part 1 of 2.)

26  2009 Pearson Education, Inc. All rights reserved. 26 Outline Interest.vb ( 2 of 3 ) Fig. 6.8 | For … Next statement used to calculate compound interest. (Part 2 of 2.)

27  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.

28  2009 Pearson Education, Inc. All rights reserved. 28 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 count A, B, C, D and F grades. (Part 1 of 6.)

29  2009 Pearson Education, Inc. All rights reserved. 29 Outline GradeBook.vb ( 2 of 6 ) Fig. 6.9 | GradeBook class uses Select … Case statement to count A, B, C, D and F grades. (Part 2 of 6.)

30  2009 Pearson Education, Inc. All rights reserved. 30 Outline GradeBook.vb ( 3 of 6 ) Fig. 6.9 | GradeBook class uses Select … Case statement to count A, B, C, D and F grades. (Part 3 of 6.)

31  2009 Pearson Education, Inc. All rights reserved. 31 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 count A, B, C, D and F grades. (Part 4 of 6.)

32  2009 Pearson Education, Inc. All rights reserved. 32 Outline GradeBook.vb ( 5 of 6 ) Fig. 6.9 | GradeBook class uses Select … Case statement to count A, B, C, D and F grades. (Part 5 of 6.)

33  2009 Pearson Education, Inc. All rights reserved. 33 Outline GradeBook.vb ( 6 of 6 ) Fig. 6.9 | GradeBook class uses Select … Case statement to count A, B, C, D and F grades. (Part 6 of 6.)

34  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.

35  2009 Pearson Education, Inc. All rights reserved. 35 6.5 GradeBook Case Study: Select … Case Multiple-Selection Statement (Cont.) Common Programming Error 6.3 Duplicate Case statements are logic errors. At run time, the first matching Case is executed. Common Programming Error 6.4 If 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.

36  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.)

37  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. Case s 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.

38  2009 Pearson Education, Inc. All rights reserved. 38 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 invokes its methods. (Part 1 of 2.)

39  2009 Pearson Education, Inc. All rights reserved. 39 Outline GradeBookTest.vb ( 2 of 2 ) Fig. 6.10 | GradeBookTest creates a GradeBook object and invokes its methods. (Part 2 of 2.)

40  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.

41  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.

42  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.

43  2009 Pearson Education, Inc. All rights reserved. 43 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.

44  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 or Do... Loop While statement never becomes false.

45  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.

46  2009 Pearson Education, Inc. All rights reserved. 46 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.

47  2009 Pearson Education, Inc. All rights reserved. 47 6.7 Do... Loop Until Repetition Statement (Cont.) Common Programming Error 6.5 Including an incorrect relational operator or an incorrect final 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.

48  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.

49  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.

50  2009 Pearson Education, Inc. All rights reserved. 50 Outline ExitTest.vb ( 1 of 3 ) Figure 6.15 demonstrates Exit statements. Fig. 6.15 | Exit statement in repetition statements. (Part 1 of 3.)

51  2009 Pearson Education, Inc. All rights reserved. 51 Outline ExitTest.vb ( 2 of 3 ) Fig. 6.15 | Exit statement in repetition statements. (Part 2 of 3.)

52  2009 Pearson Education, Inc. All rights reserved. 52 Outline ExitTest.vb ( 3 of 3 ) Fig. 6.15 | Exit statement in repetition statements. (Part 3 of 3.)

53  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 in For... Next and While loops. Continue For increments the control variable by the Step value.

54  2009 Pearson Education, Inc. All rights reserved. 54 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.)

55  2009 Pearson Education, Inc. All rights reserved. 55 Outline ContinueTest.vb ( 2 of 3 ) Fig. 6.16 | Continue statement in repetition statements. (Part 2 of 3.)

56  2009 Pearson Education, Inc. All rights reserved. 56 Outline ContinueTest.vb ( 3 of 3 ) Fig. 6.16 | Continue statement in repetition statements. (Part 3 of 3.)

57  2009 Pearson Education, Inc. All rights reserved. 57 6.10 Logical Operators Fig. 6.17 | Truth table for the logical And operator. 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.

58  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.

59  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.2 In 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.

60  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.8 Avoid expressions with side effects in conditions, because side effects often cause subtle errors. 6.10 Logical Operators (Cont.)

61  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.

62  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.)

63  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.

64  2009 Pearson Education, Inc. All rights reserved. 64 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.)

65  2009 Pearson Education, Inc. All rights reserved. 65 Outline LogicalOperators.vb ( 2 of 4 ) Fig. 6.21 | Logical operator truth tables. (Part 2 of 4.)

66  2009 Pearson Education, Inc. All rights reserved. 66 Outline LogicalOperators.vb ( 3 of 4 ) Fig. 6.21 | Logical operator truth tables. (Part 3 of 4.)

67  2009 Pearson Education, Inc. All rights reserved. 67 Outline LogicalOperators.vb ( 4 of 4 ) Fig. 6.21 | Logical operator truth tables. (Part 4 of 4.)

68  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 order of precedence.

69  2009 Pearson Education, Inc. All rights reserved. 69 6.10 Logical Operators (Cont.) Fig. 6.22 | Precedence of the operators discussed so far. (Part 2 of 2.)

70  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.

71  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.

72  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.


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

Similar presentations


Ads by Google