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

Slides:



Advertisements
Similar presentations
Session 5 JavaScript/JScript: Control Structures II Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 2 - Control Structures Outline 2.11 Assignment Operators 2.12 Increment and Decrement Operators.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
 2008 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Chapter 5 - Control Structures - Part 2 Outline 5.1Introduction 5.2Essentials of Counter-Controlled Repetition 5.3The for Repetition Structure 5.4Examples.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Control Structures: Part 2. Introduction Essentials of Counter-Controlled Repetition For / Next Repetition Structure Examples Using the For / Next Structure.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
 2005 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved The switch Multiple-Selection Statement switch.
C How to Program, 6/e Summary © by Pearson Education, Inc. All Rights Reserved.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
1 Lecture 4 for loops and switch statements Essentials of Counter-Controlled Repetition Counter-controlled repetition requires  Name of control.
 2003 Prentice Hall, Inc. All rights reserved. 1 Control Structures Outline Assignment Operators Increment and Decrement Operators Essentials of Counter-Controlled.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
1 CSCE 1030 Computer Science 1 Control Statements in Java.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (Switch, do-while, break) Outline 4.7The.
Chapter 4 C Program Control. Objectives In this chapter, you will learn: –To be able to use the for and do … while repetition statements. –To understand.
 2009 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
University of Palestine software engineering department Introduction to data structures Control Statements: Part 1 instructor: Tasneem Darwish.
Spring 2005, Gülcihan Özdemir Dağ Lecture 5, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 5 Outline 5.0 Revisiting.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
Sections 5.1 – 5.4 © Copyright by Pearson Education, Inc. All Rights Reserved.
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1 Introduction 5.2 Essentials of Counter-Controlled.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction principles BZUPAGES.COM.
 2009 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
 2002 Prentice Hall. All rights reserved. 1 Chapter 4 – Control Structures Part 1 Outline Counter-Controlled Repetition: Example Sentinel-Controlled Repetition:
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
A DVANCED P ROGRAMMING C HAPTER 5 & 6: C ONTROL S TRUCTURES Dr Shahriar Bijani Spring 2016.
 2001 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - JavaScript: Control Structures II Outline 9.1 Introduction 9.2 Essentials of Counter-Controlled.
 2005 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
 2007 Pearson Education, Inc. All rights reserved Control Statements: Part2.
 2007 Pearson Education, Inc. All rights reserved C Program Control.
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. ECE 2551 Dr. S. Kozaitis Fall Chapter 5 - Control Statements: Part 2 Outline 5.3 for Repetition.
 2008 Pearson Education, Inc. All rights reserved Control Statements: Part 2.
Chapter 4 – C Program Control
Control Statements: Part 2
Chapter 5- Control Structures: Part 2
Control Statements: Part 2
Chapter 4 - Program Control
JavaScript: Control Statements II
MSIS 655 Advanced Business Applications Programming
Advanced Programming Chapters 5 & 6: Control Structures
4 C Program Control.
Chapter 6 Control Statements: Part 2
2.6 The if/else Selection Structure
Chapter 5 – Control Structures: Part 2
Chapter 4 - Program Control
Presentation transcript:

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

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

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

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

Jozef Goetz, 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

Jozef Goetz, 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

Jozef Goetz, 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

 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 while ( counter <= 5 )// 2 repetition condition 13 { 14 Console.WriteLine("{0}”,counter ); 15 counter++; // 3 increment } // end while } // end method Main } // end class WhileCounter 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

Jozef Goetz, 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;

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

Jozef Goetz, 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

Jozef Goetz, 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

Jozef Goetz, 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 while ( counter <= 5 )// 2 repetition condition 13 { 14 Console.WriteLine("{0}”,counter ); 15 counter++; // 3 increment } // end while

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

 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 } Fig. 6.4 | UML activity diagram for the for statement in Fig. 6.2.

Jozef Goetz, 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).

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

Jozef Goetz, 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 ; }

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

Jozef Goetz, 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 )

Jozef Goetz, 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

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

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

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

Jozef Goetz, Examples Using the for Structure

Jozef Goetz, Examples Using the for Structure

Jozef Goetz, 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

Jozef Goetz, Examples 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

 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 ) ; 12 double rate =.05; 13 string output; output = "Year\tAmount on deposit\n"; for ( int year = 1; year <= 10; year++ ) 18 { 19 amount = principal * 20 ( decimal ) Math.Pow( rate, year ); output += year + "\t" + 23 String.Format( "{0:C}", amount ) + "\n"; // {0} represents the argument being displayed 24 } MessageBox.Show( output, "Compound Interest", 27 MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main } // 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 ) ⁿ

Jozef Goetz,

Jozef Goetz, Outline  Different solution:  Interest.cs Year Amount on deposit 1 $1, $1, $1, $1, $1, $1, $1, $1, $1, $1,628.89

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

Jozef Goetz, 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}”

Jozef Goetz, Examples 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 > > Total >  Use the data type Decimal (16 bytes) for monetary calculations  Do not use variables of type double (or float)

Jozef Goetz, 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

Jozef Goetz,  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.

Jozef Goetz, 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

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

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

Jozef Goetz, 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

Jozef Goetz, Fig | 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.

 2002 Prentice Hall. All rights reserved. Outline 42 SwitchTest.cs 1 // Fig 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 for ( int i = 1; i <= 10; i++ ) 18 { 19 Console.Write( "Enter a letter grade: " ); 20 grade = Char.Parse( Console.ReadLine() ); switch ( grade ) 23 { 24 case 'A': // grade is uppercase A 25 case 'a': // or lowercase a 26 ++aCount; 27 break; 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

 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; case 'D': // grade is uppercase D 40 case 'd': // or lowercase d 41 ++dCount; 42 break; case 'F': // grade is uppercase F 45 case 'f': // or lowercase f 46 ++fCount; 47 break; default: // processes all other characters 50 Console.WriteLine( 51 "Incorrect letter grade entered." + 52 "\nGrade not added to totals." ); 53 break; } // end switch } // end for 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 ); } // end method Main } // 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

Jozef Goetz, Outline  GradeBook Test.cs

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

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

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

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

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

Jozef Goetz, Outline  GradeBook Test.cs

Jozef Goetz, 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

Jozef Goetz, 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

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

 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; for ( count = 1; count <= 10; count++ ) 15 { 16 if ( count == 5 ) 17 break; // skip remaining code in loop 18 // if count == output += count + " "; } // end for loop 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 ); } // end method Main } // 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

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

 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 = ""; for ( int count = 1; count <= 10; count++ ) 14 { 15 if ( count == 5 ) 16 continue; // skip remaining code in loop 17 // only if count == output += count + " "; 20 } output += "\nUsed continue to skip printing 5"; MessageBox.Show( output, "Using the continue statement", 25 MessageBoxButtons.OK, MessageBoxIcon.Information ); } // end method Main } // 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.

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

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

Jozef Goetz, 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

Jozef Goetz, Logical 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 (||)

Jozef Goetz, Logical 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

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

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

 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 ) ); // 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 ) ); // 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

 2002 Prentice Hall. All rights reserved. Outline 65 LogicalOperators.cs Program Output Notice in ed4: lines 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

Jozef Goetz, Logical and Conditional Operators Fig | Precedence/associativity of the operators discussed so far.

Jozef Goetz, 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

Jozef Goetz, 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)

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

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

Jozef Goetz, Structured Programming Summary

Jozef Goetz, Fig | Simplest activity diagram.

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

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

Jozef Goetz, Fig | “Unstructured” activity diagram.

Jozef Goetz, 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

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

Jozef Goetz, 2012

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