Top Banner
1 2006 Pearson Education, Inc. All rights rese 6 Control Statements: Part 2
88

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

Dec 19, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 2006 Pearson Education, Inc. All rights reserved. 1 6 6 Control Statements: Part 2.

1

2006 Pearson Education, Inc. All rights reserved.

66

Control Statements: Part 2

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

2

2006 Pearson Education, Inc. All rights reserved.

Not everything that can be counted counts, and not every thing that counts can be counted.

— Albert Einstein

Who can control his fate? — William Shakespeare

The used key is always bright.— Benjamin Franklin

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

3

2006 Pearson Education, Inc. All rights reserved.

Every advantage in the past is judged in the light of the final issue.

— Demosthenes

Intelligence …is the faculty of making artificial objects, especially tools to make tools.

— Henri Bergson

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

4

2006 Pearson Education, Inc. All rights reserved.

OBJECTIVESIn this chapter you will learn: The essentials of counter-controlled

repetition. To use the for and do...while repetition

statements to execute statements in an application repeatedly.

To understand multiple selection using the switch selection statement.

To use the break and continue program control statements to alter the flow of control.

To use the logical operators to form complex conditional expressions in control statements.

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

5

2006 Pearson Education, Inc. All rights reserved.

6.1 Introduction

6.2 Essentials of Counter-Controlled Repetition

6.3 for Repetition Statement

6.4 Examples Using the for Statement

6.5 do…while Repetition Statement

6.6 switch Multiple-Selection Statement

6.7 break and continue Statements

6.8 Logical Operators

6.9 Structured Programming Summary

6.10 (Optional) Software Engineering Case Study: Identifying Objects’ States and Activities in the ATM System

6.11 Wrap-Up

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

6

2006 Pearson Education, Inc. All rights reserved.

6.1 Introduction

• Continue structured-programming discussion– Introduce C#’s remaining control structures

• for, do…while, switch

– Introduce the break and continue statements

– Introduce the logical operators

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

7

2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 6.1

Because floating-point values may be approximate, controlling loops with floating-point variables may result in imprecise counter values and inaccurate termination tests.

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

8

2006 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 6.1

Control counting loops with integers.

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

9

2006 Pearson Education, Inc. All rights reserved.

6.2 Essentials of Counter-Controlled Repetition

• Counter-controlled repetition requires:– Control variable (loop counter)

– Initial value of the control variable

– Increment/decrement of control variable through each loop

– Loop-continuation condition that tests for the final value of the control variable

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

10

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 6.1: WhileCounter.cs

2 // Counter-controlled repetition with the while repetition statement.

3 using System;

4

5 public class WhileCounter

6 {

7 public static void Main( string[] args )

8 {

9 int counter = 1; // declare and initialize control variable

10

11 while ( counter <= 10 ) // loop-continuation condition

12 {

13 Console.Write( "{0} ", counter );

14 counter++; // increment control variable

15 } // end while

16

17 Console.WriteLine(); // output a newline

18 } // end Main

19 } // end class WhileCounter 1 2 3 4 5 6 7 8 9 10

Outline

WhileCounter.cs

Control-variable name is counter

Control-variable initial value is 1

Condition tests for counter’s final value

Increment for counter

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

11

2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 6.1

Place blank lines above and below repetition and selection control statements, and indent the statement bodies to enhance readability.

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

12

2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 6.1

“Keep it simple” is good advice for most of the code you will write.

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

13

2006 Pearson Education, Inc. All rights reserved.

6.3 for Repetition Statement

• Handles counter-controlled-repetition details

• Format:for ( initialization; loopContinuationCondition; increment )

statement;

– If the counter is initialize in the For…Next header, then that variable has a scope of that loop.

• Can usually be rewritten as:initialization;while ( loopContinuationCondition )

{ statement; increment;}

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

14

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 6.2: ForCounter.cs

2 // Counter-controlled repetition with the for repetition statement.

3 using System;

4

5 public class ForCounter

6 {

7 public static void Main( string[] args )

8 {

9 // for statement header includes initialization,

10 // loop-continuation condition and increment

11 for ( int counter = 1; counter <= 10; counter++ )

12 Console.Write( "{0} ", counter );

13

14 Console.WriteLine(); // output a newline

15 } // end Main

16 } // end class ForCounter 1 2 3 4 5 6 7 8 9 10

Outline

ForCounter.cs

Control-variable name is counter

Control-variable initial value is 1

Condition tests for counter’s final value

Increment for counter

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

15

2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 6.2

Using an incorrect relational operator or an incorrect final value of a loop counter in the loop-continuation condition of a repetition statement causes an off-by-one error.

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

16

2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 6.2

Using the final value in the condition of a while or for statement with the <= relational operator helps avoid off-by-one errors. For a loop that prints the values 1 to 10, the loop-continuation condition should be counter <= 10, rather than counter < 10 (which causes an off-by-one error) or counter < 11 (which is correct). Many programmers prefer so-called zero-based counting, in which to count 10 times, counter would be initialized to zero and the loop-continuation test would be counter < 10.

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

17

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.3 | for statement header components.

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

18

2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 6.3

Using commas instead of the two required semicolons in a for header is a syntax error.

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

19

2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 6.4

When a for statement’s control variable is declared in the initialization section of the for’s header, using the control variable after the for’s body is a compilation error.

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

20

2006 Pearson Education, Inc. All rights reserved.

Performance Tip 6.1

There is a slight performance advantage to using the prefix increment operator, but if you choose the postfix increment operator because it seems more natural (as in a for header), optimizing compilers will generate MSIL code that uses the more efficient form anyway.

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

21

2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 6.3

In many cases, the prefix and postfix increment operators are both used to add 1 to a variable in a statement by itself. In these cases, the effect is exactly the same, except that the prefix increment operator has a slight performance advantage. Given that the compiler typically optimizes your code to help you get the best performance, use the idiom (prefix or postfix) with which you feel most comfortable in these situations.

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

22

2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 6.5

Placing a semicolon immediately to the right of the right parenthesis of a for header makes that for’s body an empty statement. This is normally a logic error.

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

23

2006 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 6.2

Infinite loops occur when the loop-continuation condition in a repetition statement never becomes false. To prevent this situation in a counter-controlled loop, ensure that the control variable is incremented (or decremented) during each iteration of the loop. In a sentinel-controlled loop, ensure that the sentinel value is eventually input.

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

24

2006 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 6.3

Although the value of the control variable can be changed in the body of a for loop, avoid doing so, because this practice can lead to subtle errors.

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

25

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.4 | UML activity diagram for the for statement in Fig. 6.2.

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

26

2006 Pearson Education, Inc. All rights reserved.

6.4 Examples Using the for Statement

• Varying control variable in for headers– Vary control variable from 1 to 100 in increments of 1

• for ( int i = 1; i <= 100; i++ )

– Vary control variable from 100 to 1 in increments of –1• for ( int i = 100; i >= 1; i-- )

– Vary control variable from 7 to 77 in increments of 7• for ( int i = 7; i <= 77; i += 7 )

– Vary control variable from 20 to 2 in decrements of -2• for ( int i = 20; i >= 2; i -= 2 )

– Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20• for ( int i = 2; i <= 20; i += 3 )

– Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0• for ( int i = 99; i >= 0; i -= 11 )

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

27

2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 6.6

Not using the proper relational operator in the loop-continuation condition of a loop that counts downward (e.g., using i <= 1 instead of i >= 1 in a loop counting down to 1) is a logic error.

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

28

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 6.5: Sum.cs

2 // Summing integers with the for statement.

3 using System;

4

5 public class Sum

6 {

7 public static void Main( string[] args )

8 {

9 int total = 0; // initialize total

10

11 // total even integers from 2 through 20

12 for ( int number = 2; number <= 20; number += 2 )

13 total += number;

14

15 Console.WriteLine( "Sum is {0}", total ); // display results

16 } // end Main

17 } // end class Sum Sum is 110

Outline

Sum.cs

increment number by 2 each iteration

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

29

2006 Pearson Education, Inc. All rights reserved.

6.4 Examples Using the for Statement (Cont.)

• Initialization and increment expression can be comma-separated lists of expressions

– E.g., lines 12-13 of Fig. 6.5 can be rewritten as

for ( int number = 2; number <= 20; total += number, number += 2 )

; // empty statement

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

30

2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 6.4

Limit the size of control statement headers to a single line if possible.

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

31

2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 6.5

Place only expressions involving the control variables in the initialization and increment sections of a for statement. Manipulations of other variables should appear either before the loop (if they execute only once, like initialization statements) or in the body of the loop (if they execute once per iteration of the loop, like increment or decrement statements).

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

32

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 6.6: Interest.cs

2 // Compound-interest calculations with for.

3 using System;

4

5 public class Interest

6 {

7 public static void Main( string[] args )

8 {

9 decimal amount; // amount on deposit at end of each year

10 decimal principal = 1000; // initial amount before interest

11 double rate = 0.05; // interest rate

12

13 // display headers

14 Console.WriteLine( "{0}{1,20}", "Year", "Amount on deposit" );

Outline

Interest.cs

(1 of 2)

Second string is right justified and displayed with a field width of 20

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

33

2006 Pearson Education, Inc. All rights reserved.

15

16 // calculate amount on deposit for each of ten years

17 for ( int year = 1; year <= 10; year++ )

18 {

19 // calculate new amount for specified year

20 amount = principal *

21 ( ( decimal ) Math.Pow( 1.0 + rate, year ) );

22

23 // display the year and the amount

24 Console.WriteLine( "{0,4}{1,20:C}", year, amount );

25 } // end for

26 } // end Main

27 } // end class Interest Year Amount on deposit 1 $1,050.00

2 $1,102.50 3 $1,157.63 4 $1,215.51

5 $1,276.28 6 $1,340.10 7 $1,407.10

8 $1,477.46 9 $1,551.33 10 $1,628.89

Outline

Interest.cs

(2 of 2)

Calculate amount with for statement

amount is displayed right justified in currency format

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

34

2006 Pearson Education, Inc. All rights reserved.

6.4 Examples Using the for Statement (Cont.)

• Formatting output Ex: {1, 20}– Field width is after the comma

– Right justified

– To left justify, use the minus sign (-)

•static method– ClassName.methodName( arguments)

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

35

2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 6.6

Do not use variables of type double (or float) to perform precise monetary calculations; use type decimal instead. The imprecision of floating-point numbers can cause errors that will result in incorrect monetary values.

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

36

2006 Pearson Education, Inc. All rights reserved.

Performance Tip 6.2

In loops, avoid calculations for which the result never changes—such calculations should typically be placed before the loop. [Note: Optimizing compilers will typically place such calculations outside loops in the compiled code.]

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

37

2006 Pearson Education, Inc. All rights reserved.

6.5 do…while Repetition Statement

•do…while structure– Similar to while structure

– Tests loop-continuation after performing body of loop• i.e., loop body always executes at least once

• Format:

do

statement;

while ( condition );

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

38

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 6.7: DoWhileTest.cs

2 // do...while repetition statement.

3 using System;

4

5 public class DoWhileTest

6 {

7 public static void Main( string[] args )

8 {

9 int counter = 1; // initialize counter

10

11 do

12 {

13 Console.Write( "{0} ", counter );

14 counter++;

15 } while ( counter <= 10 ); // end do...while

16

17 Console.WriteLine(); // outputs a newline

18 } // end Main

19 } // end class DoWhileTest 1 2 3 4 5 6 7 8 9 10

Outline

DoWhileTest.cs

Declares and initializes control variable counter

Variable counter’s value is displayed before testing counter’s final value

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

39

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.8 | do while repetition statement UML activity diagram.

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

40

2006 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 6.4

Always include braces in a do...while statement, even if they are not necessary. This helps eliminate ambiguity between while statements and do...while statements containing only one statement.

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

41

2006 Pearson Education, Inc. All rights reserved.

6.6 switch Multiple-Selection Statement

•switch statement– Used for multiple selections

• Each case must have a break – Exception: case body is empty and it falls through to

another case

• Goes to default if none of the cases matches– Optional

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

42

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 6.9: GradeBook.cs

2 // GradeBook class uses switch statement to count A, B, C, D and F grades.

3 using System;

4

5 public class GradeBook

6 {

7 private string courseName; // name of course this GradeBook represents

8 private int total; // sum of grades

9 private int gradeCounter; // number of grades entered

10 private int aCount; // count of A grades

11 private int bCount; // count of B grades

12 private int cCount; // count of C grades

13 private int dCount; // count of D grades

14 private int fCount; // count of F grades

15

16 // constructor initializes courseName;

17 // int instance variables are initialized to 0 by default

18 public GradeBook( string name )

19 {

20 CourseName = name; // initializes courseName

21 } // end constructor

Outline

GradeBook.cs

(1 of 5)

Variables to be incremented determined by the switch

statement

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

43

2006 Pearson Education, Inc. All rights reserved.

22

23 // property that gets and sets the course name

24 public string CourseName

25 {

26 get

27 {

28 return courseName;

29 } // end get

30 set

31 {

32 courseName = value;

33 } // end set

34 } // end property CourseName

35

36 // display a welcome message to the GradeBook user

37 public void DisplayMessage()

38 {

39 // CourseName gets the name of the course

40 Console.WriteLine( "Welcome to the grade book for\n{0}!\n",

41 CourseName );

42 } // end method DisplayMessage

Outline

GradeBook.cs

(2 of 5)

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

44

2006 Pearson Education, Inc. All rights reserved.

Outline

GradeBook.cs

(3 of 5)

43

44 // input arbitrary number of grades from user

45 public void InputGrades()

46 {

47 int grade; // grade entered by user

48 string input; // text entered by the user

49

50 Console.WriteLine( "{0}\n{1}",

51 "Enter the integer grades in the range 0-100.",

52 "Type <Ctrl> z and press Enter to terminate input:" );

53

54 input = Console.ReadLine(); // read user input

55

56 // loop until user enters the end-of-file indicator (<Ctrl> z)

57 while ( input != null )

58 {

59 grade = Convert.ToInt32( input ); // read grade off user input

60 total += grade; // add grade to total

61 gradeCounter++; // increment number of grades

62

63 // call method to increment appropriate counter

64 IncrementLetterGradeCounter( grade );

65

66 input = Console.ReadLine(); // read user input

67 } // end while

68 } // end method InputGrades

Display prompt

Loop condition: if there is more data input

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

45

2006 Pearson Education, Inc. All rights reserved.

Outline

GradeBook.cs

(4 of 5)

69

70 // add 1 to appropriate counter for specified grade

71 private void IncrementLetterGradeCounter( int grade )

72 {

73 // determine which grade was entered

74 switch ( grade / 10 )

75 {

76 case 9: // grade was in the 90s

77 case 10: // grade was 100

78 aCount++; // increment aCount

79 break; // necessary to exit switch

80 case 8: // grade was between 80 and 89

81 bCount++; // increment bCount

82 break; // exit switch

83 case 7: // grade was between 70 and 79

84 cCount++; // increment cCount

85 break; // exit switch

86 case 6: // grade was between 60 and 69

87 dCount++; // increment dCount

88 break; // exit switch

89 default: // grade was less than 60

90 fCount++; // increment fCount

91 break; // exit switch

92 } // end switch

93 } // end method IncrementLetterGradeCounter

switch statement determines which case label to execute,

depending on controlling expression

(grade / 10 ) is the controlling expression

default case for grade less than 60

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

46

2006 Pearson Education, Inc. All rights reserved.

Outline

GradeBook.cs

(5 of 5)

94

95 // display a report based on the grades entered by the user

96 public void DisplayGradeReport()

97 {

98 Console.WriteLine( "\nGrade Report:" );

99

100 // if user entered at least one grade...

101 if ( gradeCounter != 0 )

102 {

103 // calculate average of all grades entered

104 double average = ( double ) total / gradeCounter;

105

106 // output summary of results

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

108 gradeCounter, total );

109 Console.WriteLine( "Class average is {0:F2}", average );

110 Console.WriteLine( "{0}A: {1}\nB: {2}\nC: {3}\nD: {4}\nF: {5}",

111 "Number of students who received each grade:\n",

112 aCount, // display number of A grades

113 bCount, // display number of B grades

114 cCount, // display number of C grades

115 dCount, // display number of D grades

116 fCount ); // display number of F grades

117 } // end if

118 else // no grades were entered, so output appropriate message

119 Console.WriteLine( "No grades were entered" );

120 } // end method DisplayGradeReport

121 } // end class GradeBook

Prints out results

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

47

2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 6.7

Forgetting a break statement when one is needed in a switch is a syntax error.

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

48

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 6.10: GradeBookTest.cs

2 // Create GradeBook object, input grades and display grade report.

3

4 public class GradeBookTest

5 {

6 public static void Main( string[] args )

7 {

8 // create GradeBook object myGradeBook and

9 // pass course name to constructor

10 GradeBook myGradeBook = new GradeBook(

11 "CS101 Introduction to C# Programming" );

12

13 myGradeBook.DisplayMessage(); // display welcome message

14 myGradeBook.InputGrades(); // read grades from user

15 myGradeBook.DisplayGradeReport(); // display report based on grades

16 } // end Main

17 } // end class GradeBookTest

Outline

GradeBookTest.cs

(1 of 2)

Call GradeBook public methods to count grades

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

49

2006 Pearson Education, Inc. All rights reserved.

Welcome to the grade book for CS101 Introduction to C# Programming! Enter the integer grades in the range 0-100. Type <Ctrl> z and press Enter to terminate input:

99 92 45 100 57 63 76 14 92 ^Z

Grade Report: Total of the 9 grades entered is 638 Class average is 70.89 Number of students who received each grade: A: 4 B: 0 C: 1 D: 1 F: 3

Outline

GradeBookTest.cs

(2 of 2)

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

50

2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 6.2

Provide a default label in switch statements. Cases not explicitly tested in a switch that lacks a default label are ignored. Including a default label focuses you on the need to process exceptional conditions.

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

51

2006 Pearson Education, Inc. All rights reserved.

Good Programming Practice 6.7

Although each case and the default label in a switch can occur in any order, place the default label last for clarity.

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

52

2006 Pearson Education, Inc. All rights reserved.

6.6 switch Multiple-Selection Statement (Cont.)

• Utility / helper methods– private methods to support other methods

• Expression in each case– Constant integral expression

• Combination of integer constants that evaluates to a constant integer value

– Character constant• E.g., ‘A’, ‘7’ or ‘$’

– Constant variable

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

53

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.11 | switch multiple-selection statement UML activity diagram with break statements.

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

54

2006 Pearson Education, Inc. All rights reserved.

6.7 break and continue Statements

•break/continue– Alter flow of control

•break statement – Causes immediate exit from control structure

• Used in while, for, do…while, switch, or foreach statements

•continue statement – Skips remaining statements in loop body

– Proceeds to next iteration• Used in while, for, do…while or foreach statements

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

55

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 6.12: BreakTest.cs

2 // break statement exiting a for statement.

3 using System;

4

5 public class BreakTest

6 {

7 public static void Main( string[] args )

8 {

9 int count; // control variable also used after loop terminates

10

11 for ( count = 1; count <= 10; count++ ) // loop 10 times

12 {

13 if ( count == 5 ) // if count is 5,

14 break; // terminate loop

15

16 Console.Write( "{0} ", count );

17 } // end for

18

19 Console.WriteLine( "\nBroke out of loop at count = {0}", count );

20 } // end Main

21 } // end class BreakTest 1 2 3 4 Broke out of loop at count = 5

Outline

BreakTest.csLoop 10 times

Exit for statement (break) when count equals 5

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

56

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 6.13: ContinueTest.cs

2 // continue statement terminating an iteration of a for statement.

3 using System;

4

5 public class ContinueTest

6 {

7 public static void Main( string[] args )

8 {

9 for ( int count = 1; count <= 10; count++ ) // loop 10 times

10 {

11 if ( count == 5 ) // if count is 5,

12 continue; // skip remaining code in loop

13

14 Console.Write( "{0} ", count );

15 } // end for

16

17 Console.WriteLine( "\nUsed continue to skip printing 5" );

18 } // end Main

19 } // end class ContinueTest 1 2 3 4 6 7 8 9 10 Used continue to skip printing 5

Outline

ContinueTest.csLoop 10 times

Skip line 14 and proceed to line 9 when count equals 5

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

57

2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 6.3

Some programmers feel that break and continue statements violate structured programming. Since the same effects are achievable with structured programming techniques, these programmers prefer not to use break or continue statements.

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

58

2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 6.4

There is a tension between achieving quality software engineering and achieving the best-performing software. Often, one of these goals is achieved at the expense of the other. For all but the most performance-intensive situations, apply the following rule of thumb: First, make your code simple and correct; then make it fast and small, but only if necessary.

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

59

2006 Pearson Education, Inc. All rights reserved.

6.8 Logical Operators

• Logical operators– Allows for forming more complex conditions

– Combines simple conditions

• C# logical operators– && (conditional AND)

– || (conditional OR)

– & (boolean logical AND)

– | (boolean logical inclusive OR)

– ^ (boolean logical exclusive OR)

– ! (logical NOT)

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

60

2006 Pearson Education, Inc. All rights reserved.

6.8 Logical Operators (Cont.)

• Conditional AND (&&) Operator– Consider the following if statement

if ( gender == FEMALE && age >= 65 )

seniorFemales++;

– Combined condition is true • if and only if both simple conditions are true

– Combined condition is false • if either or both of the simple conditions are false

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

61

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.14 | && (conditional AND) operator truth table.

expression1 expression2 expression1 && expression2

false false false

false true false

true false false

true true true

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

62

2006 Pearson Education, Inc. All rights reserved.

6.8 Logical Operators (Cont.)

• Conditional OR (||) Operator– Consider the following if statement

if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 )

Console.WriteLine( “Student grade is A” );

– Combined condition is true • if either or both of the simple condition are true

– Combined condition is false • if both of the simple conditions are false

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

63

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.15 | || (conditional OR) operator truth table.

expression1 expression2 expression1 || expression2

false false false

false true true

true false true

true true true

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

64

2006 Pearson Education, Inc. All rights reserved.

6.8 Logical Operators (Cont.)

• Short-Circuit Evaluation of Complex Conditions– Parts of an expression containing && or || operators are

evaluated only until it is known whether the condition is true or false

– E.g., ( gender == FEMALE ) && ( age >= 65 )• Stops immediately if gender is not equal to FEMALE

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

65

2006 Pearson Education, Inc. All rights reserved.

Common Programming Error 6.8

In expressions using operator &&, a condition—which we refer to as the dependent condition—may require another condition to be true for the evaluation of the dependent condition to be meaningful. In this case, the dependent condition should be placed after the other condition, or an error might occur. For example, in the expression ( i != 0 ) && ( 10 / i == 2 ), the second condition must appear after the first condition, or a divide-by-zero error might occur.

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

66

2006 Pearson Education, Inc. All rights reserved.

6.8 Logical Operators (Cont.)

• Boolean Logical AND (&) Operator– Works identically to &&

– Except & always evaluate both operands

• Boolean Logical OR (|) Operator – Works identically to ||

– Except | always evaluate both operands

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

67

2006 Pearson Education, Inc. All rights reserved.

Error-Prevention Tip 6.5

For clarity, avoid expressions with side effects in conditions. The side effects may look clever, but they can make it harder to understand code and can lead to subtle logic errors.

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

68

2006 Pearson Education, Inc. All rights reserved.

6.8 Logical Operators (Cont.)

• Boolean Logical Exclusive OR (^)– One of its operands is true and the other is false

• Evaluates to true

– Both operands are true or both are false• Evaluates to false

• Logical Negation (!) Operator– Unary operator

– Opposite of the boolean value

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

69

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.16 | ^ (boolean logical exclusive OR) operator truth table.

expression1 expression2 expression1 ^ expression2

false false false

false true true

true false true

true true false

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

70

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.17 | ! (logical negation) operator truth table.

expression !expression

false true

true false

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

71

2006 Pearson Education, Inc. All rights reserved.

1 // Fig. 6.18: LogicalOperators.cs

2 // Logical operators.

3 using System;

4

5 public class LogicalOperators

6 {

7 public static void Main( string[] args )

8 {

9 // create truth table for && (conditional AND) operator

10 Console.WriteLine( "{0}\n{1}: {2}\n{3}: {4}\n{5}: {6}\n{7}: {8}\n",

11 "Conditional AND (&&)", "false && false", ( false && false ),

12 "false && true", ( false && true ),

13 "true && false", ( true && false ),

14 "true && true", ( true && true ) );

15

16 // create truth table for || (conditional OR) operator

17 Console.WriteLine( "{0}\n{1}: {2}\n{3}: {4}\n{5}: {6}\n{7}: {8}\n",

18 "Conditional OR (||)", "false || false", ( false || false ),

19 "false || true", ( false || true ),

20 "true || false", ( true || false ),

21 "true || true", ( true || true ) );

22

23 // create truth table for & (boolean logical AND) operator

24 Console.WriteLine( "{0}\n{1}: {2}\n{3}: {4}\n{5}: {6}\n{7}: {8}\n",

25 "Boolean logical AND (&)", "false & false", ( false & false ),

26 "false & true", ( false & true ),

27 "true & false", ( true & false ),

28 "true & true", ( true & true ) );

Outline

LogicalOperators.cs

(1 of 3)

Conditional AND truth operator

Boolean logical AND operator

Conditional OR truth operator

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

72

2006 Pearson Education, Inc. All rights reserved.

29

30 // create truth table for | (boolean logical inclusive OR) operator

31 Console.WriteLine( "{0}\n{1}: {2}\n{3}: {4}\n{5}: {6}\n{7}: {8}\n",

32 "Boolean logical inclusive OR (|)",

33 "false | false", ( false | false ),

34 "false | true", ( false | true ),

35 "true | false", ( true | false ),

36 "true | true", ( true | true ) );

37

38 // create truth table for ^ (boolean logical exclusive OR) operator

39 Console.WriteLine( "{0}\n{1}: {2}\n{3}: {4}\n{5}: {6}\n{7}: {8}\n",

40 "Boolean logical exclusive OR (^)",

41 "false ^ false", ( false ^ false ),

42 "false ^ true", ( false ^ true ),

43 "true ^ false", ( true ^ false ),

44 "true ^ true", ( true ^ true ) );

45

46 // create truth table for ! (logical negation) operator

47 Console.WriteLine( "{0}\n{1}: {2}\n{3}: {4}",

48 "Logical negation (!)", "!false", ( !false ),

49 "!true", ( !true ) );

50 } // end Main

51 } // end class LogicalOperators

Outline

LogicalOperators.cs

(2 of 3)

Boolean logical inclusive OR operator

Boolean logical exclusive OR operator

Logical negation operator

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

73

2006 Pearson Education, Inc. All rights reserved.

Conditional AND (&&) false && false: False false && true: False true && false: False true && true: True Conditional OR (||) false || false: False false || true: True true || false: True true || true: True Boolean logical AND (&) false & false: False false & true: False true & false: False true & true: True Boolean logical inclusive OR (|) false | false: False false | true: True true | false: True true | true: True Boolean logical exclusive OR (^) false ^ false: False false ^ true: True true ^ false: True true ^ true: False Logical negation (!) !false: True !true: False

Outline

LogicalOperators.cs

(3 of 3)

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

74

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.19 | Precedence/associativity of the operators discussed so far.

Operators Associativity Type

. new ++(postfix) --(postfix) left to right highest precedence

++ -- + - ! (type) right to left unary prefix

* / % left to right multiplicative

+ - left to right additive

< <= > >= left to right relational

== != left to right equality

& left to right boolean logical AND

^ left to right boolean logical exclusive OR

| left to right boolean logical inclusive OR

&& left to right conditional AND

|| left to right conditional OR

?: right to left conditional

= += -= *= /= %= right to left assignment

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

75

2006 Pearson Education, Inc. All rights reserved.

6.9 Structured Programming Summary

• Sequence structure– “built-in” to C#

• Selection structure– if, if…else and switch

• Repetition structure– while, do…while, for, and foreach

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

76

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.20 | C#’s single-entry/single-exit sequence, selection and repetition statements.

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

77

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.21 | Rules for forming structured applications.

Rules for Forming Structured Applications

1 Begin with the simplest activity diagram (Fig. 6.22).

2 Any action state can be replaced by two action states in sequence.

3 Any action state can be replaced by any control statement (sequence of action states, if, if else, switch, while, do while, for or foreach, which we will see in Chapter 8).

4 Rules 2 and 3 can be applied as often as necessary in any order.

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

78

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.22 | Simplest activity diagram.

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

79

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.23 | Repeatedly applying the stacking rule (Rule 2) of Fig. 6.21 to the simplest activity diagram.

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

80

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.24 | Repeatedly applying the nesting rule (Rule 3) of Fig. 6.21 to the simplest activity diagram.

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

81

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.25 | “Unstructured” activity diagram.

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

82

2006 Pearson Education, Inc. All rights reserved.

6.10 (Optional) Software Engineering Case Study: Identifying Objects’ State and Activities in the ATM System• State Machine Diagrams

– Commonly called state diagram

– Model several states of an object

– Show under what circumstances the object changes state

– Focus on system behavior

– UML representation• State

- Rounded rectangle

• Initial state

- Solid circle

• Transitions

- Arrows with stick arrowheads

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

83

2006 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 6.5

Software designers do not generally create state machine diagrams showing every possible state and state transition for all attributes—there are simply too many of them. State machine diagrams typically show only the most important or complex states and state transitions.

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

84

2006 Pearson Education, Inc. All rights reserved.

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

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

85

2006 Pearson Education, Inc. All rights reserved.

6.10 (Optional) Software Engineering Case Study: Identifying Objects’ State and Activities in the ATM System (Cont.)• Activity Diagrams

– Focus on system behavior

– Model an object’s workflow during program execution

– Model the actions the object will perform and in what order

– UML representation• Action state ( rectangle with its left and right sides replaced

by arcs curving outwards)

• Action order ( arrow with a stick arrowhead)

• Initial state (solid circle)

• Final state (solid circle enclosed in an open circle)

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

86

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.27 | Activity diagram for a BalanceInquiry transaction.

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

87

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.28 | Activity diagram for a Withdrawal transaction.

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

88

2006 Pearson Education, Inc. All rights reserved.

Fig. 6.29 | Activity diagram for a Deposit transaction.