jozef goetz, 2012 1 2011 pearson education, inc. all rights reserved. 2002 prentice hall. all...
TRANSCRIPT
Jozef Goetz, 2012
1
2011 Pearson Education, Inc. All rights reserved.
2002 Prentice Hall. All rights reserved.
expanded by J. Goetz, 2012
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
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
Jozef Goetz, 2012
4Objectives
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, 2012
5
Chapter 6 – Control Structures: Part 2
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
Jozef Goetz, 2012
66.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
Jozef Goetz, 2012
76.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
2002 Prentice Hall.All rights reserved.
Outline8
WhileCounter.cs
Program Output
1 // Fig. 6.1: WhileCounter.cs2 // Counter-controlled repetition.3 4 using System;5 6 class WhileCounter7 {8 static void Main( string[] args )9 {10 int counter = 1; // 1 initialization11 12 while ( counter <= 5 )// 2 repetition condition13 {14 Console.WriteLine("{0}”,counter );15 counter++; // 3 increment16 17 } // end while18 19 } // end method Main20 21 } // end class WhileCounter
12345
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, 2012
96.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;
Jozef Goetz, 2012
10Common 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, 2012
116.3 for Repetition Structure
for ( int counter = 1; counter <= 5; counter++ )
Initial value of control variable Increment of control variable
Control variable name Final value of control variablefor keyword
Loop-continuation condition (test)
Fig. 6.3 Components of a typical for header.
•Handles counter-controlled-repetition details
Jozef Goetz, 2012
126.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
Jozef Goetz, 2012
136.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.4 Flowcharting a typical for repetition structure.
10 int counter = 1; // 1 initialization11 12 while ( counter <= 5 )// 2 repetition condition13 {14 Console.WriteLine("{0}”,counter );15 counter++; // 3 increment16 17 } // end while
Jozef Goetz, 2012
14 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 <= 5; 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
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.
Outline15
ForCounter.cs
Program Output
1 // Fig. 6.2: ForCounter.cs2 // Counter-controlled repetition with the for structure.3 4 using System;5 6 class ForCounter7 {8 static void Main( string[] args )9 {10 // initialization, repetition condition and incrementing11 // are all included in the for structure12 for ( int counter = 1; counter <= 5; counter++ )13 Console.WriteLine( “{0}”, counter );14 }15 }
12345
Fig. 6.4 | UML activity diagram for the for statement in Fig. 6.2.
Jozef Goetz, 2012
166.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).
Jozef Goetz, 2012
176.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.
Jozef Goetz, 2012
186.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;}
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 incrementoperator, optimizing compilers will generate MSIL code that uses the more efficient form.
6.3 for Repetition Statement
Common Programming Error 6.5Placing 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, 2012
206.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 = 10for ( int j = x; j <= 4 * x * y; j += y / x )
equivalent tofor ( int j = 2; j <= 80; j += 5 )
Jozef Goetz, 2012
216.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
Jozef Goetz, 2012
22Error-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, 2012
23
1 // Fig. 6.5: Sum.cs
2 // Summing even 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
Example program:
Sum all the even integers from 2 to 20
Jozef Goetz, 2012
246.4 Examples Using the for Structure
Massages boxes Icons
Exclamation Question Error Information
Message boxes Buttons
OK OKCancel YesNo AbortRetryIgnore YesNoCancel RetryCancel
Jozef Goetz, 2012
256.4 Examples Using the for Structure
MessageBox Icons Icon Description MessageBoxIcon.Exclamation
Displays a dialog with an exclamation point. Typically used to caution the user against potential problems.
MessageBoxIcon.Information
Displays a dialog with an informational message to the user.
MessageBoxIcon.Question
Displays a dialog with a question mark. Typically used to ask the user a question.
MessageBoxIcon.Error
Displays a dialog with an x in a red circle. Helps alert user of errors or important messages.
Fig. Icons for message dialogs.
Jozef Goetz, 2012
266.4 Examples Using the for Structure
MessageBox Buttons Description MessageBoxButton.OK Specifies that the dialog should include an OK button.
MessageBoxButton.OKCancel Specifies that the dialog should include OK and Cancel buttons. Warns the user about some condition and allows the user to either continue or cancel an operation.
MessageBoxButton.YesNo Specifies that the dialog should contain Yes and No buttons. Used to ask the user a question.
MessageBoxButton.YesNoCancel Specifies that the dialog should contain Yes, No and Cancel buttons. Typically used to ask the user a question but still allows the user to cancel the operation.
MessageBoxButton.RetryCancel Specifies that the dialog should contain Retry and Cancel buttons. Typically used to inform a user about a failed operation and allow the user to retry or cancel the operation.
MessageBoxButton.AbortRetryIgnore Specifies that the dialog should contain Abort, Retry and Ignore buttons. Typically used to inform the user that one of a series of operations has failed and allow the user to abort the series of operations, retry the failed operation or ignore the failed operation and continue.
Fig. Buttons for message dialogs.
Jozef Goetz, 2012
276.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
Jozef Goetz, 2012
286.4 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 );
Math.pow( x, y )
Raises x to the yth power Takes two doubles, returns a double
2002 Prentice Hall.All rights reserved.
Outline29
Interest.cs
1 // Fig. 5.8 ed1: Interest.cs2 // Calculating compound interest.3 4 using System;5 using System.Windows.Forms;6 7 class Interest8 {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 displayed24 }25 26 MessageBox.Show( output, "Compound Interest", 27 MessageBoxButtons.OK, MessageBoxIcon.Information );28 29 } // end method Main30 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 Tab
Formats amount to have a currency formatting ($0.00)
// a = p (1 + r ) ⁿ
Jozef Goetz, 2012
30
Jozef Goetz, 2012
31 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
Different solution:
Interest.cs 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 );// a field width of // 20 chrs with right justification, -20 is left justification 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
Jozef Goetz, 2012
326.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 (-)
Jozef Goetz, 2012
336.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}”
Format Specifier Description
C or c Formats the string as currency. Precedes the number with an appropriate currency symbol ($ in the US). Separates digits with an appropriate separator character (comma in the US) and sets the number of decimal places to two by default.
D or d Formats the string as a decimal. Displays number as an integer.
N or n Formats the string with commas and a default of two decimal places.
E or e Formats the number using scientific notation with a default of six decimal places.
F or f Formats the string with a fixed number of decimal places (two by default).
G or g General. Formats the number normally with decimal places or using scientific notation, depending on context. If a format item does not contain a format specifier, format G is assumed implicitly.
X or x Formats the string as hexadecimal.
Jozef Goetz, 2012
346.4 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) Person14.234 -> 14.23 14.2318.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)
Jozef Goetz, 2012
356.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 loop1. Action is performed2. Then the loop condition is tested3. Loop must be run though once
Using a while loop1. Condition is tested2. The action is performed3. Loop could be skipped altogether
true
false
action(s)
condition
Jozef Goetz, 2012
36 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
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, 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
Jozef Goetz, 2012
386.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.
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 ErrorForgetting a break statement when one is needed in a switch is a compilation error.
6.6 The switch Multiple-Selection Structure
Jozef Goetz, 2012
406.6 switch Multiple-Selection Structure
break;
case: a case a action(s)true
false
.
.
.
break;
case b action(s) break;
false
false
case: z case z action(s) break;
default action(s)
true
true
case: b
Fig. 6.11 Flowcharting 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, 2012
41Fig. 6.11 | switch multiple-selection statement UML activity diagram with
break statements.
Common Programming ErrorForgetting a break statement when one is needed in a switch is a compilation error.
Good Programming Practice 6.4Although 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.
Outline42
SwitchTest.cs
1 // Fig. 6.10 ed1: SwitchTest.cs2 // Counting letter grades.3 4 using System;5 6 class SwitchTest7 {8 static void Main( string[] args )9 {10 char grade; // one grade11 int aCount = 0, // number of As12 bCount = 0, // number of Bs13 cCount = 0, // number of Cs14 dCount = 0, // number of Ds15 fCount = 0; // number of Fs16 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 A25 case 'a': // or lowercase a26 ++aCount;27 break;28 29 case 'B': // grade is uppercase B30 case 'b': // or lowercase b31 ++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: aEnter a letter grade: AEnter a letter grade: cEnter a letter grade: FEnter a letter grade: zIncorrect letter grade entered.Grade not added to totals.Enter a letter grade: DEnter a letter grade: dEnter a letter grade: BEnter a letter grade: aEnter a letter grade: C Totals for each letter grade are:A: 3B: 1C: 2D: 2F: 1
2002 Prentice Hall.All rights reserved.
Outline43
SwitchTest.cs
34 case 'C': // grade is uppercase C35 case 'c': // or lowercase c36 ++cCount;37 break;38 39 case 'D': // grade is uppercase D40 case 'd': // or lowercase d41 ++dCount;42 break;43 44 case 'F': // grade is uppercase F45 case 'f': // or lowercase f46 ++fCount;47 break;48 49 default: // processes all other characters50 Console.WriteLine( 51 "Incorrect letter grade entered." +52 "\nGrade not added to totals." );53 break;54 55 } // end switch56 57 } // end for58 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 Main65 66 } // end class SwitchTest
Both cases add 1 to cCount
If 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: aEnter a letter grade: AEnter a letter grade: cEnter a letter grade: FEnter a letter grade: zIncorrect letter grade entered.Grade not added to totals.Enter a letter grade: DEnter a letter grade: dEnter a letter grade: BEnter a letter grade: aEnter a letter grade: C Totals for each letter grade are:A: 3B: 1C: 2D: 2F: 1
Jozef Goetz, 2012
44 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(); // 1. display welcome message
14 myGradeBook.InputGrades(); // 2. read grades from user
15 myGradeBook.DisplayGradeReport(); // 3. display report based on grades
16 } // end Main
17 } // end class GradeBookTest
Outline
GradeBookTest.cs
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
1.
2.
3.
Jozef Goetz, 2012
45 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 // automatic property CourseName
16 public string CourseName { get; set; }
// 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)
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, 2012
4622
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)
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
Jozef Goetz, 2012
47
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 (null) the end-of-file indicator ( <Ctrl> z)
57 while ( input != null ) // compare a string reference with a 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
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
Jozef Goetz, 2012
48
Outline
GradeBook.cs
(4 of 5)
69
70 // add 1 to appropriate counter for specified grade
71 private void IncrementLetterGradeCounter( int grade ) //helper
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
• A switch statement determines whether each grade is an A, B, C, D or F.
Jozef Goetz, 2012
49
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
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
Jozef Goetz, 2012
50 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
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
Jozef Goetz, 2012
516.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
Jozef Goetz, 2012
526.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
Jozef Goetz, 2012
53 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.cs
Loop 10 times
Exit for statement (break) when count equals 5
2002 Prentice Hall.All rights reserved.
Outline54
BreakTest.cs
1 // Fig. 6.12: BreakTest.cs with a MessageBox2 // Using the break statement in a for structure.3 4 using System;5 using System.Windows.Forms;6 7 class BreakTest8 {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 == 519 20 output += count + " ";21 22 } // end for loop23 24 output += "\nBroke out of loop at count = " + count;25 // Display the last value that the counter was at before it broke26 MessageBox.Show( output, "Demonstrating the break statement",27 MessageBoxButtons.OK, MessageBoxIcon.Information );28 29 } // end method Main30 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
Jozef Goetz, 2012
55 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
2002 Prentice Hall.All rights reserved.
Outline56
ContinueTest.cs
1 // Fig. 6.13: ContinueTest.cs with a MessageBox2 // Using the continue statement in a for structure.3 4 using System;5 using System.Windows.Forms;6 7 class ContinueTest8 {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 loop17 // only if count == 518 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 Main28 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.
Jozef Goetz, 2012
57Software 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, 2012
58TIPSPerformance 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, 2012
596.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
Jozef Goetz, 2012
606.8 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, 2012
616.8 Logical Operators
Examples
Expression Result
true && false falsetrue || false true
!false truetrue ^ true false
if ( ( gender == 1 ) && ( age >= 65 ) ) ++seniorFemales;
seniorFemales updated if both conditions true
Jozef Goetz, 2012
626.8 Logical and Conditional Operators
expression1 expression2 expression1 && expression2
false false false false true false true false false true true true Fig. 6.14 Truth table for the && (conditional AND) operator.
expression1 expression2 expression1 || expression2
false false false false true true true false true true true true Fig. 6.15 Truth table for the || (conditional OR) operator.
if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 ) ) Console.WriteLine ( "Student grade is A" );
Jozef Goetz, 2012
636.8 Logical and Conditional Operators
expression1 expression2 expression1 ^ expression2
false false false false true true true false true true true false Fig. 6.16 Truth table for the logical exclusive OR (^) operator.
expression !expression false true True false Fig. 6.17 Truth table for operator! (logical NOT).
if ( grade != sentinelValue ) Console.WriteLine( "The next grade is {0}", grade );
2002 Prentice Hall.All rights reserved.
Outline64
LogicalOperators.cs
1 // Fig. 6.18: LogicalOperators.cs2 // Demonstrating the logical operators.3 using System;4 5 class LogicalOperators6 {7 // main entry point for application8 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 true
Only 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: Falsefalse && true: Falsetrue && false: Falsetrue && true: True
Conditional OR (||)false || false: Falsefalse || true: Truetrue || false: Truetrue || true: True
Logical AND (&)
false & false: False
false & true: False
true & false: False
true & true: True
2002 Prentice Hall.All rights reserved.
Outline65
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 // 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 input
Returns 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, 2012
666.8 Logical and Conditional Operators
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
Fig. 6.19 | Precedence/associativity of the operators discussed
so far.
Jozef Goetz, 2012
676.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
Jozef Goetz, 2012
686.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)
Jozef Goetz, 2012
696.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.
Jozef Goetz, 2012
70Fig. 6.20 | C#’s single-entry/single-exit sequence, selection and repetition
statements.
Jozef Goetz, 2012
716.9 Structured Programming Summary
Rules for Forming Structured Programs 1) Begin with the “simplest flowchart” (Fig. 6.22). 2) The Stacking Rule. Any rectangle (action) can be replaced by two
rectangles (actions) in sequence. 3) The Nesting Rule. Any rectangle (action) can be replaced by any control
structure (sequence, if, if/else, switch, while, do/while, for or foreach, as we will see in Chapter 8).
4) Rules 2 and 3 may be applied as often as you like and in any order. Fig. 6.21 Rules for forming structured programs.
Jozef Goetz, 2012
72Fig. 6.22 | Simplest activity diagram.
Jozef Goetz, 2012
73Fig. 6.23 | Repeatedly applying the stacking rule (Rule 2) of Fig. 6.21 to the simplest activity diagram.
Jozef Goetz, 2012
74Fig. 6.24 | Repeatedly applying the nesting rule (Rule 3)
of Fig. 6.21 to the simplest activity diagram.
Jozef Goetz, 2012
75Fig. 6.25 | “Unstructured” activity diagram.
Jozef Goetz, 2012
766.9 Structured Programming Summary
Fig. 6.27 Stacked, 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, 2012
77Structured 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
Jozef Goetz, 2012
79 Output sum s for x = 0, 0.1, 0.2, …0.9, 1 in the table format