Presentation is loading. Please wait.

Presentation is loading. Please wait.

Jozef Goetz, 2012 1  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. expanded by J. Goetz, 2012.

Similar presentations


Presentation on theme: "Jozef Goetz, 2012 1  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. expanded by J. Goetz, 2012."— Presentation transcript:

1

2 Jozef Goetz, 2012 1  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. expanded by J. Goetz, 2012

3 Jozef Goetz, 2012 2  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

4 Jozef Goetz, 2012 3  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

5 Jozef Goetz, 2012 4 Objectives  The essentials of counter-controlled repetition.  To be able to use the for and do/loop while repetition structures to execute statements in a program repeatedly.  To understand multiple selection that uses the switch selection structure.  To be able to use the break and continue program- control statements.  To be able to use the logical operators.

6 Jozef Goetz, 2012 5 Chapter 6 – Control Structures: Part 2  6.1Introduction  6.2Essentials of Counter-Controlled Repetition  6.3 for Repetition Statement  6.4Examples Using the for Statement  6.5 do…while Repetition Statement  6.6 switch Multiple-Selection Statement  6.7 break and continue Statements  6.8Logical Operators  6.9Structured Programming Summary  6.10(Optional) Software Engineering Case Study: Identifying Objects’ States and Activities in the ATM System  6.11Wrap-Up

7 Jozef Goetz, 2012 6 6.1 Introduction  Before writing program  Have thorough understanding of problem  Carefully planned approach for solving it  While writing program  Know what “building blocks” are available  Use good programming principles  Continue structured-programming discussion  Introduce C#’s remaining control structures

8 Jozef Goetz, 2012 7 6.2 Essentials of Counter-Controlled Repetition  Counter-controlled repetition (CCR) requires:  Name of a control variable (loop counter)  Initial value  Condition to test for the final value (whether looping should continue)  Increment (or decrement)  Control variable modified each time through the loop  Upcoming example  Counter-controlled repetition

9  2002 Prentice Hall. All rights reserved. Outline 8 WhileCounter.cs Program Output 1 // Fig. 6.1: WhileCounter.cs 2 // Counter-controlled repetition. 3 4 using System; 5 6 class WhileCounter 7 { 8 static void Main( string[] args ) 9 { 10 int counter = 1; // 1 initialization 11 12 while ( counter <= 5 )// 2 repetition condition 13 { 14 Console.WriteLine("{0}”,counter ); 15 counter++; // 3 increment 16 17 } // end while 18 19 } // end method Main 20 21 } // end class WhileCounter 1234512345 This is where the counter variable is initialized. It is set to 1. The loop will continue until counter is greater than five (it will stop once it gets to six) The counter is incremented and 1 is added to it

10 Jozef Goetz, 2012 9 6.2 Essentials of Counter Controlled Repetition  Loop can be shortened  Initialize counter to zero  Change loop to: while ( ++counter <= 5 ) //repetition condition Console.WriteLine( counter );  The precedence of ++ is higher that of <= Good Programming Practice:  Programs should control counting loops with integer values.  Indent the body;  a blank line before & after control structure;  avoid more than 3 level of nesting;

11 Jozef Goetz, 2012 10 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.

12 Jozef Goetz, 2012 11 6.3 for Repetition Structure for (int counter = 1; counter <= 5; counter++ ) Initial value of control variableIncrement of control variable Control variablenameFinal value of control variable for keyword Loop-continuation condition (test) Fig. 6.3Components of a typical for header. Handles counter-controlled-repetition details

13 Jozef Goetz, 2012 12 6.3 for Repetition Structure  The for repetition structure  Syntax: for (Expression1; Expression2; Expression3)  Expression1 = names the control variable –Can contain several variables  Expression2 = loop-continuation condition  Expression3 = incrementing/decrementing –If Expression1 has several variables, Expression3 must have several variables accordingly –++counter and counter++ are equivalent for ( int counter = 1; counter <= 5; counter++ )  Variable scope  Expression1 can only be used in the body of the for loop  When the loop ends the variable counter expires

14 Jozef Goetz, 2012 13 6.3 for Repetition Structure counter++ Establish initial value of control variable. Determine if final value of control variable has been reached. counter <= 5 Console.WriteLine ( counter * 5 ); true false counter = 1 Body of loop (this may be multiple statements) Increment the control variable. Fig. 6.4Flowcharting a typical for repetition structure. 10 int counter = 1; // 1 initialization 11 12 while ( counter <= 5 )// 2 repetition condition 13 { 14 Console.WriteLine("{0}”,counter ); 15 counter++; // 3 increment 16 17 } // end while

15 Jozef Goetz, 2012 14 Outline  ForCounter.cs Control-variable name is counter Control-variable initial value is 1 Condition tests for counter ’s final value Increment for counter

16  2002 Prentice Hall. All rights reserved. Outline 15 ForCounter.cs Program Output 1 // Fig. 6.2: ForCounter.cs 2 // Counter-controlled repetition with the for structure. 3 4 using System; 5 6 class ForCounter 7 { 8 static void Main( string[] args ) 9 { 10 // initialization, repetition condition and incrementing 11 // are all included in the for structure 12 for ( int counter = 1; counter <= 5; counter++ ) 13 Console.WriteLine( “{0}”, counter ); 14 } 15 } 1234512345 Fig. 6.4 | UML activity diagram for the for statement in Fig. 6.2.

17 Jozef Goetz, 2012 16 6.3 The for Repetition Structure (cont.) Good Programming Practices  Place only expressions involving the control variables in the initialization and increment sections of a for structure.  Manipulations of other control 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 incrementing or decrementing statements). Common Programming Errors 6.2  When the control variable of a for structure is initially defined in the initialization section of the header of the for structure, using the control variable after the for ’s body is a compilation error (the control variable expires).

18 Jozef Goetz, 2012 17 6.3 The for Repetition Structure (cont.) – General format: for ( initialization ; loopContinuationTest ; increment ) statement; If multiple statements needed, enclose in braces Control variable only exists in body of for structure – the variable’s scope If loopContinuationTest is initially false, body not executed All three expressions in a for header are optional. Omitting the loopContinuationCondition creates an infinite loop for ( initialization ; ; increment ) //an infinite loop statement; Omitting the initialization expression can be done if the control variable is initialized before the loop. Omitting the increment expression can be done if the application calculates the increment with statements in the loop’s body or if no increment is needed.

19 Jozef Goetz, 2012 18 6.3 The for Repetition Structure (cont.) –General format: for ( initialization ; loopContinuationTest ; increment ) statement; for ( initialization ; ; increment ) //an infinite loop statement; If multiple statements needed, enclose in braces Control variable only exists in body of for structure – the variable’s scope If loopContinuationTest is initially false, body not executed for ( initialization; loopContinuationTest; increment ) statement; can usually be rewritten as an equivalent while structure: initialization ; while ( loopContinuationTest ) { statement increment ; }

20 Jozef Goetz, 2012 19 Good Programming Practice 6.2 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 but if you choose the postfix increment operator, optimizing compilers will generate MSIL code that uses the more efficient form. 6.3 for Repetition Statement 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.

21 Jozef Goetz, 2012 20 6.4 Examples Using the for Structure  Varying control variable in for structure  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 decrements of –1  for ( int i = 100; i >= 1; i-- )  It counts downward  Vary control variable from 7 to 77 in steps of 7  for ( int i = 7; i <= 77; i += 7 )  The initialization, loop-continuation condition and increment portions of a for statement can contain arithmetic expressions.  Let x = 2, y = 10 for ( int j = x; j <= 4 * x * y; j += y / x ) equivalent to for ( int j = 2; j <= 80; j += 5 )

22 Jozef Goetz, 2012 21 6.4 Examples Using the for Structure  Increment/Decrement  When incrementing  In most cases < or <= is used - avoid off-by-one error  When decrementing  In most cases > or >= is used - avoid off-by-one error  avoid off-by-one error  Using an incorrect relational operator or an incorrect final value of a loop counter in the condition of a while, for or do while statement can cause an off-by-one error or an infinite loop.  For zero-based counting test the loop if e.g. counter < 10 instead of counter <= 10 starting from counter = 0

23 Jozef Goetz, 2012 22 Error-Prevention Tip 6.2 – 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.  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.

24 Jozef Goetz, 2012 23 Outline  Sum.cs Example program: Sum all the even integers from 2 to 20

25 Jozef Goetz, 2012 24 6.4 Examples Using the for Structure Massages boxes  Icons  Exclamation  Question  Error  Information  Message boxes  Buttons  OK  OKCancel  YesNo  AbortRetryIgnore  YesNoCancel  RetryCancel

26 Jozef Goetz, 2012 25 6.4 Examples Using the for Structure

27 Jozef Goetz, 2012 26 6.4 Examples Using the for Structure

28 Jozef Goetz, 2012 27 6.4 Examples Using the for Structure  Compute compound interest  Calculate the value each year of a $1000 deposit, yielding 5% annually  Calculate the value for 10 years  Use a = p (1 + r ) ⁿ –p - principal –r - interest rate –n - number of years –a - amount on deposit after nth year  Example program  Use a for loop to calculate interest

29 Jozef Goetz, 2012 28 6.4Examples Using the for Structure  static method accesss  ClassName.MethodName( arguments)  “.” aceess operator  static methods do not need to be called on objects ( an instance of an object)  static method pow (class Math ) public static double Pow( double x, double y );double Math.pow( x, y )  Raises x to the y th power  Takes two double s, returns a double

30  2002 Prentice Hall. All rights reserved. Outline 29 Interest.cs 1 // Fig. 5.8 ed1: Interest.cs 2 // Calculating compound interest. 3 4 using System; 5 using System.Windows.Forms; 6 7 class Interest 8 { 9 static void Main( string[] args ) 10 { 11 decimal amount, principal = ( decimal ) 1000.00; 12 double rate =.05; 13 string output; 14 15 output = "Year\tAmount on deposit\n"; 16 17 for ( int year = 1; year <= 10; year++ ) 18 { 19 amount = principal * 20 ( decimal ) Math.Pow( 1.0 + rate, year ); 21 22 output += year + "\t" + 23 String.Format( "{0:C}", amount ) + "\n"; // {0} represents the argument being displayed 24 } 25 26 MessageBox.Show( output, "Compound Interest", 27 MessageBoxButtons.OK, MessageBoxIcon.Information ); 28 29 } // end method Main 30 31 } // end class Interest Creates a message box that displays the output with a title of “Compound Interest” has an OK button and an information icon Loops through 10 times starting at 1 and ending at 10, adding 1 to the counter (year) each time Insert a TabFormats amount to have a currency formatting ($0.00) // a = p (1 + r ) ⁿ

31 Jozef Goetz, 2012 30

32 Jozef Goetz, 2012 31 Outline  Different solution:  Interest.cs 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

33 Jozef Goetz, 2012 32 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 (-)

34 Jozef Goetz, 2012 33 6.4 Examples Using the for Structure Console.WriteLine( "{0,4}{1,20:C}", year, amount ); // a field width of // 20 with right justification, -20 is left justification “{1,20:F4}”

35 Jozef Goetz, 2012 34 6.4Examples Using the for Structure  Beware rounding when performing monetary calculations using 4 bytes for Float (in.NET) or 8 bytes for Double to represent dollar amount  The imprecision of floating-points (Float or Double) can cause errors (assuming displaying Double with 2 decimal places): Machine Display(rounded) Person 14.234 -> 14.23 14.23 18.673 -> 18.67 18.67 Total 32.907 -> 32.91 32.90  Use the data type Decimal (16 bytes) for monetary calculations  Do not use variables of type double (or float)

36 Jozef Goetz, 2012 35 6.5 do/while Repetition Structure  The while loops vs. the do/while loops  Format do { statement } while ( condition );  Good practice to put brackets in, even if not required  Using a do/while loop 1.Action is performed 2.Then the loop condition is tested 3.Loop must be run though once  Using a while loop 1.Condition is tested 2.The action is performed 3.Loop could be skipped altogether true false action(s) condition

37 Jozef Goetz, 2012 36  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.] Fig. 6.8 | do while repetition statement UML activity diagram.

38 Jozef Goetz, 2012 37 Error-Prevention Tip 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. 6.5 do... while Repetition Statement

39 Jozef Goetz, 2012 38 6.6 The switch Multiple-Selection Structure  switch structure  Used for multiple selections  Useful to test variable for different values  Different action taken  Format: switch ( variable){ case expr1: actions case expr2: actions … default: //optional but it is good programming practice to test it Actions // exceptional conditions }  expr1,..exprn is 1.a variable or 2.a constant integral expression value which evaluates to (byte, sbyte, short, ushort, int, uint, long, ulong or char type(e.g.‘A’) or 3.a constant string expression (is any expression composed of string literals that always result on the same string)  Series of case labels: case1: case2: actions  an optional default case  break; causes exit from structure  The switch multiple-selection statement performs different actions based on the value of an expression.  Each action is associated with the value of a constant integral expression or a constant string expression that the expression may assume.

40 Jozef Goetz, 2012 39  The expression following keyword switch is called the switch expression.  The application attempts to match the value of the switch expression with one of the case labels.  You are required to include a statement that terminates the case, such as a break, a return or a throw.  The break statement causes program control to proceed with the first statement after the switch.  If no match occurs, the statements after the default label execute. Common Programming Error Forgetting a break statement when one is needed in a switch is a compilation error. 6.6 The switch Multiple-Selection Structure

41 Jozef Goetz, 2012 40 6.6 switch Multiple-Selection Structure Fig. 6.11Flowcharting the switch multiple-selection structure.  The switch statement  Constant expressions  String  Integral  Cases  Case ‘x’ : –Use of constant variable cases  Empty cases  The default case  The break – not included is a syntax error  Exit the switch statement

42 Jozef Goetz, 2012 41 Fig. 6.11 | switch multiple-selection statement UML activity diagram with break statements. Common Programming Error Forgetting a break statement when one is needed in a switch is a compilation error. Good Programming Practice 6.4 Although each case and the default label in a switch can occur in any order, place the default label last for clarity.

43  2002 Prentice Hall. All rights reserved. Outline 42 SwitchTest.cs 1 // Fig. 6.10 ed1: SwitchTest.cs 2 // Counting letter grades. 3 4 using System; 5 6 class SwitchTest 7 { 8 static void Main( string[] args ) 9 { 10 char grade; // one grade 11 int aCount = 0, // number of As 12 bCount = 0, // number of Bs 13 cCount = 0, // number of Cs 14 dCount = 0, // number of Ds 15 fCount = 0; // number of Fs 16 17 for ( int i = 1; i <= 10; i++ ) 18 { 19 Console.Write( "Enter a letter grade: " ); 20 grade = Char.Parse( Console.ReadLine() ); 21 22 switch ( grade ) 23 { 24 case 'A': // grade is uppercase A 25 case 'a': // or lowercase a 26 ++aCount; 27 break; 28 29 case 'B': // grade is uppercase B 30 case 'b': // or lowercase b 31 ++bCount; 32 break; 33 Each of these variables acts as a counter so they are initialized to zero The start of the switch statement. The grade variable is used as the data to be tested for each case. Prompt the user for a grade and store it into the grade variable case ‘A’ is empty so it is the same as case ‘a’ The break statement is used to exit the switch statement and not perform the rest of the operations Both case ‘B’ and case ‘b’ add one to the bCount variable Enter a letter grade: a Enter a letter grade: A Enter a letter grade: c Enter a letter grade: F Enter a letter grade: z Incorrect letter grade entered. Grade not added to totals. Enter a letter grade: D Enter a letter grade: d Enter a letter grade: B Enter a letter grade: a Enter a letter grade: C Totals for each letter grade are: A: 3 B: 1 C: 2 D: 2 F: 1

44  2002 Prentice Hall. All rights reserved. Outline 43 SwitchTest.cs 34 case 'C': // grade is uppercase C 35 case 'c': // or lowercase c 36 ++cCount; 37 break; 38 39 case 'D': // grade is uppercase D 40 case 'd': // or lowercase d 41 ++dCount; 42 break; 43 44 case 'F': // grade is uppercase F 45 case 'f': // or lowercase f 46 ++fCount; 47 break; 48 49 default: // processes all other characters 50 Console.WriteLine( 51 "Incorrect letter grade entered." + 52 "\nGrade not added to totals." ); 53 break; 54 55 } // end switch 56 57 } // end for 58 59 Console.WriteLine( 60 "\nTotals for each letter grade are:\nA: {0}" + 61 "\nB: {1}\nC: {2}\nD: {3}\nF: {4}", aCount, bCount, 62 cCount, dCount, fCount ); 63 64 } // end method Main 65 66 } // end class SwitchTest Both cases add 1 to cCountIf grade equals D or d add one to dCount If non of the cases are equal to the value of grade then the default case is executed Display the results Enter a letter grade: a Enter a letter grade: A Enter a letter grade: c Enter a letter grade: F Enter a letter grade: z Incorrect letter grade entered. Grade not added to totals. Enter a letter grade: D Enter a letter grade: d Enter a letter grade: B Enter a letter grade: a Enter a letter grade: C Totals for each letter grade are: A: 3 B: 1 C: 2 D: 2 F: 1

45 Jozef Goetz, 2012 44 Outline  GradeBook Test.cs 1. 2. 3.

46 Jozef Goetz, 2012 45 Outline  GradeBook.cs  (1 of 5) Keeping track of the sum of the grades and the number of grades entered, for averaging. Counter variables for each grade category. Figure 6.9 contains an enhanced version of the GradeBook class.

47 Jozef Goetz, 2012 46 Outline  GradeBook.cs  (2 of 5)

48 Jozef Goetz, 2012 47 Outline  GradeBook.cs  (3 of 5)

49 Jozef Goetz, 2012 48 Outline  GradeBook.cs  (4 of 5) A switch statement determines whether each grade is an A, B, C, D or F.

50 Jozef Goetz, 2012 49 Outline  GradeBook.cs  (5 of 5)

51 Jozef Goetz, 2012 50 Outline  GradeBook Test.cs

52 Jozef Goetz, 2012 51 6.7 Statements break and continue  Alter the flow of control  break statement  Causes immediate exit from control structure  Used in while, for, do/while or switch statements  Program continues with the first statement after the structure  Common uses of the break statement  Escape early from a loop  Skip the remainder of a switch structure  continue statement  Skips the remaining statements in body of while, for or do/while  Proceeds with the next iteration of the loop  while and do/while  Loop-continuation test is evaluated immediately after continue  for structure  Increment expression is executed, then the loop-continuation test is evaluated

53 Jozef Goetz, 2012 52 6.7 Statements break and continue  Used to alter the flow of control  The break statement  Used to exit a loop early  The continue statement  Used to skip the rest of the statements and begin the loop at the first statement in the loop  Programs can be completed without their usage

54 Jozef Goetz, 2012 53 Outline  BreakTest. cs Loop 10 times Exit for statement ( break ) when count equals 5

55  2002 Prentice Hall. All rights reserved. Outline 54 BreakTest.cs 1 // Fig. 6.12: BreakTest.cs with a MessageBox 2 // Using the break statement in a for structure. 3 4 using System; 5 using System.Windows.Forms; 6 7 class BreakTest 8 { 9 static void Main( string[] args ) 10 { 11 string output = ""; 12 int count; 13 14 for ( count = 1; count <= 10; count++ ) 15 { 16 if ( count == 5 ) 17 break; // skip remaining code in loop 18 // if count == 5 19 20 output += count + " "; 21 22 } // end for loop 23 24 output += "\nBroke out of loop at count = " + count; 25 // Display the last value that the counter was at before it broke 26 MessageBox.Show( output, "Demonstrating the break statement", 27 MessageBoxButtons.OK, MessageBoxIcon.Information ); 28 29 } // end method Main 30 31 } // end class BreakTest Displays a message box the displays the output, has a title of “demonstrating the break statement,” uses an OK button, and displays an information icon A loop that starts at one, goes to ten, and increments by one If count = 5 then break out of the loop

56 Jozef Goetz, 2012 55 Outline  ContinueTest.cs Loop 10 times Skip line 14 and proceed to line 9 when count equals 5

57  2002 Prentice Hall. All rights reserved. Outline 56 ContinueTest.cs 1 // Fig. 6.13: ContinueTest.cs with a MessageBox 2 // Using the continue statement in a for structure. 3 4 using System; 5 using System.Windows.Forms; 6 7 class ContinueTest 8 { 9 static void Main( string[] args ) 10 { 11 string output = ""; 12 13 for ( int count = 1; count <= 10; count++ ) 14 { 15 if ( count == 5 ) 16 continue; // skip remaining code in loop 17 // only if count == 5 18 19 output += count + " "; 20 } 21 22 output += "\nUsed continue to skip printing 5"; 23 24 MessageBox.Show( output, "Using the continue statement", 25 MessageBoxButtons.OK, MessageBoxIcon.Information ); 26 27 } // end method Main 28 29 } // end class ContinueTest A loop that starts at 1, goes to 10, and increments by 1 If count = 5 then continue looping causing the program to skip the rest of the loop Create a message box that displays the output, has the title “using the continue statement,” uses an button, and displays an information icon.

58 Jozef Goetz, 2012 57 Software Engineering Observation 6.2  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.

59 Jozef Goetz, 2012 58 TIPS Performance Tips The break and continue statements, when used properly, perform faster than the corresponding structured techniques. Software Engineering Observation  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.

60 Jozef Goetz, 2012 59 6.8 Logical and Conditional Operators  Used to add multiple conditions to a statement  Operators  Allows for forming more complex conditions  Combines simple conditions  Logical AND (&), Conditional AND (&&)  Returns true if both conditions are true  Logical OR (|), Conditional OR (||)  Returns true if either of its conditions are true  Logical exclusive OR or XOR (^)  Returns false when the two conditionals are the same  Logical NOT (!)  Reverses the truth/falsity of its condition  Unary operator, has one operand  Can be avoided if desired by using other conditional operators

61 Jozef Goetz, 2012 60 6.8Logical Operators  Logical Operators  & (Logical exclusive OR or XOR )  true if exactly one condition true  | (inclusive OR) = Boolean logical OR  All logical operators & and | always evaluates both expressions (no short-circuit evaluation) –Useful if right operand has a needed side effect birthday == true | ++age >= 65 –Avoid expressions with side effects – more trouble than they are worth.  Short circuit evaluation is applied only to Conditional AND (&&) and OR (||):  Evaluate left operand, decide whether to evaluate right operand  If left operand of && is false, will not evaluate right operand  Boolean logical AND ( & ) and OR( |) work identical to conditional AND (&&) and logical OR (||)

62 Jozef Goetz, 2012 61 6.8Logical Operators  Examples ExpressionResult true && false false true || false true !false true true ^ truefalse  if ( ( gender == 1 ) && ( age >= 65 ) ) ++seniorFemales;  seniorFemales updated if both conditions true

63 Jozef Goetz, 2012 62 6.8 Logical and Conditional Operators if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 ) ) Console.WriteLine ( "Student grade is A" );

64 Jozef Goetz, 2012 63 6.8 Logical and Conditional Operators if ( grade != sentinelValue ) Console.WriteLine( "The next grade is {0}", grade );

65  2002 Prentice Hall. All rights reserved. Outline 64 LogicalOperators.cs 1 // Fig. 6.18: LogicalOperators.cs 2 // Demonstrating the logical operators. 3 using System; 4 5 class LogicalOperators 6 { 7 // main entry point for application 8 static void Main( string[] args ) 9 { 10 // testing the conditional AND operator (&&) 11 Console.WriteLine( "Conditional AND (&&)" + 12 "\nfalse && false: " + ( false && false ) + 13 "\nfalse && true: " + ( false && true ) + 14 "\ntrue && false: " + ( true && false ) + 15 "\ntrue && true: " + ( true && true ) ); 16 17 // testing the conditional OR operator (||) 18 Console.WriteLine( "\n\nConditional OR (||)" + 19 "\nfalse || false: " + ( false || false ) + 20 "\nfalse || true: " + ( false || true ) + 21 "\ntrue || false: " + ( true || false ) + 22 "\ntrue || true: " + ( true || true ) ); 23 24 // testing the logical AND operator (&) 25 Console.WriteLine( "\n\nLogical AND (&)" + 26 "\nfalse & false: " + ( false & false ) + 27 "\nfalse & true: " + ( false & true ) + 28 "\ntrue & false: " + ( true & false ) + 29 "\ntrue & true: " + ( true & true ) ); 30 Only true if both inputs are trueOnly false if both inputs are false The result is only true if both are true Outputs a truth table for the conditional AND operator (&&) Outputs a truth table for the conditional OR operator (||) Outputs a truth table for the logical AND operator (&) 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 Logical AND (&) false & false: False false & true: False true & false: False true & true: True

66  2002 Prentice Hall. All rights reserved. Outline 65 LogicalOperators.cs Program Output Notice in ed4: lines 38-44 have different output format than others 31 // testing the logical OR operator (|) 32 Console.WriteLine( "\n\nLogical OR (|)" + 33 "\nfalse | false: " + ( false | false ) + 34 "\nfalse | true: " + ( false | true ) + 35 "\ntrue | false: " + ( true | false ) + 36 "\ntrue | 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 // testing the logical NOT operator (!) 46 Console.WriteLine( "\n\nLogical NOT (!)" + 47 "\n!false: " + ( !false ) + 48 "\n!true: " + ( !true ) ); 49 } 50 } Returns the opposite as the inputReturns false when the two conditionals are the same If one is true the result is true Outputs a truth table for the logical OR operator (||) Outputs a truth table for the logical exclusive OR operator (||) Outputs a truth table for the logical NOT operator (!) Logical OR (|) false | false: False false | true: True true | false: True true | true: True Logical exclusive OR (^) false ^ false: False false ^ true: True true ^ false: True true ^ true: False Logical NOT (!) !false: True !true: False

67 Jozef Goetz, 2012 66 6.8 Logical and Conditional Operators Fig. 6.19 | Precedence/associativity of the operators discussed so far.

68 Jozef Goetz, 2012 67 6.9 Structured Programming Summary  Produces programs that are:  easy to understand,  test,  debug and  modify them and  even prove correct in a mathematical sense.  Control Structures  Only one entrance  Only one exit  Building blocks to programming  Allow nesting  Makes code neater and easier to follow  No overlapping structures  The goto keyword

69 Jozef Goetz, 2012 68 6.9 Structured Programming Summary  3 forms of control necessary  Many ways to implement these controls  Sequential (only 1 way)  Straight forward programming  Selection (3 ways)  if selection (one choice)  if/else selection (two choices)  switch statement (multiple choices)  Repetition (4 ways)  while structure  do/while structure  for structure  foreach structure (chapter 7)

70 Jozef Goetz, 2012 69 6.9 Structured Programming Summary  Connecting control structures: the exit point of one control structure connects to the entry point the next control structure (control- structure stacking).  Any these control structures can be combined in only 2 ways: control-structure stacking and nesting.

71 Jozef Goetz, 2012 70 Fig. 6.20 | C#’s single-entry/single-exit sequence, selection and repetition statements.

72 Jozef Goetz, 2012 71 6.9 Structured Programming Summary

73 Jozef Goetz, 2012 72 Fig. 6.22 | Simplest activity diagram.

74 Jozef Goetz, 2012 73 Fig. 6.23 | Repeatedly applying the stacking rule (Rule 2) of Fig. 6.21 to the simplest activity diagram.

75 Jozef Goetz, 2012 74 Fig. 6.24 | Repeatedly applying the nesting rule (Rule 3) of Fig. 6.21 to the simplest activity diagram.

76 Jozef Goetz, 2012 75 Fig. 6.25 | “Unstructured” activity diagram.

77 Jozef Goetz, 2012 76 6.9 Structured Programming Summary Fig. 6.27Stacked, nested and overlapped building blocks. Stacked building blocks Overlapping building blocks (illegal in structured programs) Nested building blocks Combination of control structures: 1.Stacking Placing one after another 2.Nesting Inserting of one structure into another

78 Jozef Goetz, 2012 77 Structured Programming Summary  All programs can be written in terms of 3 control structures Sequence, Selection and Repetition (Bohm and Jacopini)  All structured programs can be broken down into 3 parts  Sequence - trivial  Selection - if, if/else, or switch  Can be rewritten as an if statement  Repetition - while, do/while, or for  Can be rewritten as a while statement  Structured programs can be reduced by applying rules 1-4 in reverse to the simplest flowchart.

79 Jozef Goetz, 2012

80 79 Output sum s for x = 0, 0.1, 0.2, …0.9, 1 in the table format 


Download ppt "Jozef Goetz, 2012 1  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved. expanded by J. Goetz, 2012."

Similar presentations


Ads by Google